我有一个基类,然后是它的两个派生类。我正在使用基类的指针来存储Vector中的派生类对象。现在我要打印存储在矢量C++多态性在一个向量中存储基类指针
我怎么能检索的矢量对象中的数据。
我怎样才能确保到派生类检索的对象所属。
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);
}
这里我使用向量来存储载体中的对象。
INT主要(){
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;
}
我已经试过甚至通过会员访问[我] - > getType()以及但没有任何发生 – ProgrammingNinja