C++ 多级遗传与多态性

C++ 多级遗传与多态性,c++,inheritance,polymorphism,multiple-inheritance,C++,Inheritance,Polymorphism,Multiple Inheritance,当我运行程序时,我得到的输出是 主叫男性足球运动员,类型为:男性足球运动员 我正在创建一个基类指针footballplayer,并将其分配给派生类objectmalefootballplayer,它应该调用属于基类的函数,因为它不是虚拟的,并且输出应该是“调用类footballplayer,类型是:Football Player” 希望把我的概念弄清楚 谢谢。由于MaleFootballPlayer对象的地址包含在FootballPlayer类型指针中,并且printType方法在基本实现中声明

当我运行程序时,我得到的输出是

主叫男性足球运动员,类型为:男性足球运动员

我正在创建一个基类指针footballplayer,并将其分配给派生类objectmalefootballplayer,它应该调用属于基类的函数,因为它不是虚拟的,并且输出应该是“调用类footballplayer,类型是:Football Player”

希望把我的概念弄清楚


谢谢。

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

Player::printType声明为虚拟。更重要的是,虚拟不会消失,只是因为它没有在派生类中重复。@arne,如果virtual关键字在派生类中重复会怎么样?都一样。如果函数在任何基类中声明为虚函数,则无论关键字virtual是否重复,它对于任何和所有派生类都是虚函数。C++11提供了最后一个关键字,可以阻止实现者进一步重载函数,但最派生的实现仍将从基类指针或引用调用。
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; 
}