【问题标题】:Multilevel Inheritance and Polymorphism多级继承和多态
【发布时间】:2013-10-21 05:04:23
【问题描述】:
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 ,类型为:足球运动员'。

希望澄清我的概念。

谢谢。

【问题讨论】:

  • Player::printType 声明virtual.

标签: c++ inheritance polymorphism multiple-inheritance


【解决方案1】:

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

【讨论】:

  • 更重要的是,virtual 不会因为它没有在派生类中重复而消失。
  • @arne,如果“virtual”关键字在派生类中重复出现怎么办?
  • 都是一样的。如果函数在任何基类中声明为virtual,则无论是否重复关键字virtual,它对于任何和所有派生类都是虚函数。 C++11 提供了final 关键字,可以阻止实现者进一步重载函数,但仍然会从基类指针或引用中调用最派生的实现。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-13
  • 2011-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-18
相关资源
最近更新 更多