class Player
{
protected:
string type;
int rank;
public:
virtual void printType()
{
cout<<"Calling Class Player, type is: general Player"<<endl;
}
};
//class FootballPlayer: Derived from Player
class FootballPlayer: public Player
{
protected:
public:
virtual void printRank()
{
cout<<"Calling Class FootballPlayer, Rank is: Football Player rank"<<endl;
}
void printType()
{
cout<<"Calling Class FootballPlayer, type is: Football Player"<<endl;
}
};
class MaleFootballPlayer: public FootballPlayer
{
public:
void printType()
{
cout<<"Calling Class MaleFootballPlayer, type is: Male Football Player"<<endl;
}
void printRank()
{
cout<<"Calling Class MaleFootballPlayer, Rank is: Male Player rank"<<endl;
}
};
//class CricketPlayer: Derived from Player
class CricketPlayer: public Player
{
protected:
public:
void printType()
{
cout<<"Calling Class CricketPlayer, type is: Cricket Player"<<endl;
}
};
int main(int argc, const char * argv[])
{
FootballPlayer fbplayer;
CricketPlayer crplayer;
MaleFootballPlayer malefbplayer;
FootballPlayer *fbplayerPtr;
fbplayerPtr=&malefbplayer;
fbplayerPtr->printType();
return 0;
}
当我运行程序时,我得到的输出是,
调用类MaleFootballPlayer,输入是:男子足球运动员
我正在创建一个基类指针(footballplayer)并分配给派生类对象(malefootballplayer),它应该调用属于基类的函数(因为它不是虚拟的),输出应该是'调用类FootBallPlayer ,类型是:足球运动员'。
希望清除我的概念。
感谢。
答案 0 :(得分:0)
由于MaleFootballPlayer对象的地址包含在FootballPlayer类型指针中,而printType()方法在基本实现中声明为virtual,因此派生类MaleFootballPlayer函数会覆盖它。这就是为什么会这样。 虚拟表包含两个类的两个printType()函数的指针,但运行时选择了派生类printType()函数指针。