|
-
February 23rd, 2010, 07:01 PM
#1
Vectors and Multiple classes
I have a vector of pointers to baseball players as indicated below
Code:
vector<BaseballPlayer*> team;
// stores information regarding a team
along with an iterator to traverse through the vector
Code:
vector<'NOT SURE WHAT TO DEFINE THIS AS'>::iterator Trav_Team;
// iterator to traverse through a team
The purpose of this function is to store the different class objects into the vector which will later be used to print a player's information
Code:
void PlayerDatabase::load_team(ifstream &playerINPUT)
{
Pitcher * ptrPitcher;
Hitter * ptrHitter;
int pos;
cout <<"Initializing team count = 0\n" << endl;
char player_Position;
// player's position on the team
// while there is still input, continuing reading the file
// and incrementing team count until EOF occurs
while(playerINPUT >> player_Position)
{
/* check to see if the player is a pitcher or hitter */
if(player_Position == 'P')
{
ptrPitcher = new Pitcher;
ptrPitcher->load_player(playerINPUT);
team.push_back(reinterpret_cast<BaseballPlayer*>(ptrPitcher));
//stores the Pitcher's information (object) into the team vector
}
else if(player_Position == 'H')
{
ptrHitter = new Hitter;
ptrHitter->load_player(playerINPUT);
team.push_back(reinterpret_cast<BaseballPlayer*>(ptrHitter));
//stores the Hitter's information (object) into the team vector
}
team_count++;
//increment total members on team and positioning
cout <<"Loading member " << team_count << endl;
}//end of while loop
}
When I create a routine to traverse through the team vector to print out the player information, if they are either a pitcher or hitter, it doesn't work, because the iterator is only of a certain type. How can I get the iterator access both the Pitcher and Hitter classes? Or if there is another method I'm not aware of.
-
February 23rd, 2010, 07:11 PM
#2
Re: Vectors and Multiple classes
If your Pitcher and Hitter classes are properly deriving from BaseballPlayer, it should work automatically. Furthermore, the reinterpret_cast should not be necessary.
-
February 24th, 2010, 05:48 PM
#3
Re: Vectors and Multiple classes
Code:
vector<'NOT SURE WHAT TO DEFINE THIS AS'>::iterator Trav_Team;
In general the typename used to create the vector is the same that is used to create the iterator for that container type.
Code:
vector<int> values;
vector<int>::iterator iter;
vector<BasebalPlayer*> team;
vector<BasebalPlayer*>::iterator teamIter;
If you want more help you need to post more complete examples of what you are doing. Post a complete example preferrably as a single, compilable, unit with the three classes and a small main function that demonstrates the problem.
Last edited by kempofighter; February 24th, 2010 at 05:51 PM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|