1
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,类型是: 足球运动员'。

希望清除我的概念。

谢谢。

4

1 回答 1

0

由于 MaleFootballPlayer 对象的地址包含在 FootballPlayer 类型指针和在基本实现中声明为虚拟的 printType() 方法中,因此派生类 MaleFootballPlayer 函数会在运行时覆盖它。这就是为什么发生这种情况。虚拟表包含两个类的 printType() 函数的指针,但运行时选择了派生类 printType() 函数指针。

于 2013-10-21T05:39:58.913 回答