如何在多重继承的情况下初始化派生类成员

时间:2021-03-04 01:24:50

标签: c++ virtual multiple-inheritance

我有以下程序。当我尝试执行它时,我发现 Allrounder 没有得到有效的名称。知道我该如何解决吗?

#include <iostream>
#include <string>
using namespace std;

class Player
{
    std::string playerName;
public:
    Player(std::string &playerName) :playerName(playerName) { cout << "Player Constructed\n"; }
    void printPlayerName() const
    {
        std::cout<<playerName<<endl;
    }
    Player() = default;
    virtual ~Player() { cout << "Player Destructed\n"; }
};

class Batsman : virtual public Player
{
public:
    Batsman(std::string playerName) : Player(playerName) { cout << "Batsman info added\n"; }
    ~Batsman() { cout << "Batsman Destructed\n"; }
};

class Bowler : virtual public Player
{
public:
    Bowler(std::string playerName) : Player(playerName) { cout << "Bowler info added\n"; }
    ~Bowler() { cout << "Bowler Destructed\n"; }
};

class Allrounder : public Batsman, public Bowler
{
public:
    Allrounder(std::string playerName) :Batsman(playerName), Bowler(playerName) { cout << "Allrounder info added"; }
    ~Allrounder() { cout << "Allrounder Destructed\n"; }
};

int main()
{
    Player *ptr = new Batsman("Sachin Tendulkar");
    ptr->printPlayerName();
    delete ptr;
    cout << endl;
    Player *ptr1 = new Bowler("Anil Kumble");
    ptr1->printPlayerName();
    delete ptr1;
    cout << endl;
    Player * ptr2 = new Allrounder("Ravindra Jadeja");
    ptr2->printPlayerName();
    delete ptr2;
    cout << endl;
}

我确保调用超类构造函数,但在多重继承的情况下,这似乎不起作用。

当前 ptr2->printPlayerName() 无法打印 Allrounder 的名称。

0 个答案:

没有答案