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

问题描述

我有以下程序。当我尝试执行它时,我发现 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名称

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)