我有一个基类,然后有两个派生类。我使用基类的指针来存储Vector中的派生类对象。现在我必须打印存储在vector
中的数据如何从矢量中检索对象。
如何确保检索到的对象属于哪个派生类。
class CricketPlayer:public SlumsMember
{
protected:
int runsScored;
int wicketsTaken;
int catchesTaken;
public:
CricketPlayer(int rNo,string n,double theGpa,char typ,int rScore,int theWicketTaken,int theCatchTaken);
int getRunsScored();
int getWicketsTaken();
int getCatchesTaken();
};
CricketPlayer::CricketPlayer(int rNo,string n,double theGpa,char typ,int rScore,int theWicketTaken,int theCatchTaken):
SlumsMember(rNo,n,theGpa,typ)
{
runsScored=rScore;
wicketsTaken=theWicketTaken;
catchesTaken=theCatchTaken;
}
int CricketPlayer::getRunsScored()
{
return (runsScored);
}
int CricketPlayer::getWicketsTaken()
{
return (wicketsTaken);
}
int CricketPlayer::getCatchesTaken()
{
return(catchesTaken);
}
class FootballPlayer:public SlumsMember
{
protected:
int goalsScored;
int assists;
int interceptions;
public:
FootballPlayer(int rNo,string n,double theGpa,char typ,int theGoalsScored,int theAssists,int theInterceptions);
int getGoalsScored();
int getAssists();
int getInterceptions();
};
FootballPlayer::FootballPlayer(int rNo,string n,double theGpa,char typ,int theGoalsScored,int theAssists,int theInterceptions):
SlumsMember(rNo,n,theGpa,typ)
{
goalsScored=theGoalsScored;
assists=theAssists;
interceptions=theInterceptions;
}
int FootballPlayer::getGoalsScored()
{
return(goalsScored);
}
int FootballPlayer::getAssists()
{
return(assists);
}
int FootballPlayer::getInterceptions()
{
return(interceptions);
}
这里我使用vector来存储矢量中的对象。
int main(){
vector<SlumsMember> members;
SlumsMember *slumsMember;
slumsMember=new FootballPlayer(rNo,name,gpa,ch,a,b,c);
slumsMember=new CricketPlayer(rNo,name,gpa,ch,a,b,c);
members.push_back(*slumsMember);
SlumsMember *mbr;
for(int i=0;i<members.size();i++)
{
mbr=members[i];
//How to make sure to which base class an object retrieved belongs to and how to access it.
}
return 0;
}
答案 0 :(得分:1)
我清理了你的代码......
class SlumsMember
{
试试这个......让getWicketsTaken函数在基类
中变为虚拟public:
virtual int getWicketsTaken();
int rollNumber;
string name;
double gpa;
char type;
};
class CricketPlayer:public SlumsMember
{
public:
覆盖有助于防止类型超载
int getWicketsTaken() override;
int runsScored;
int wicketsTaken;
int catchesTaken;
};
class FootballPlayer: public SlumsMember
{
Then you can override the getWicketsTaken in this class too
int getWicketsTaken() override;
public:
int goalsScored;
int assists;
int interceptions;
};
int main() {
vector<SlumsMember*> members;
请注意,在下一行,如果您提供的值不是贫民窟成员,则应收到编译错误。
members.push_back(new FootballPlayer(rNo,name,gpa,ch,a,b,c));
members.push_back(new CricketPlayer(rNo,name,gpa,ch,a,b,c));
SlumsMember *mbr;
for(int i=0;i<members.size();i++)
{
mbr=members[i];
//How to make sure to which base class an object retrieved belongs to and how to access it.
int rollNumber = mbr->rollNumber;
double gpa = mbr->gpa;
等...并且不要忘记在某个时刻释放你的对象,这样你就不会出现内存泄漏
}
return 0;
}