我有一個基類,然後是它的兩個派生類。我正在使用基類的指針來存儲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