如何从 DerivedClass 参数设置 BaseClass 变量

How to set BaseClass variable from DerivedClass parameter

我有 类 Player 和 HumanPlayer。 HumanPlayer 派生自 Player.

class Player {
private:
    int id;
protected:
    string name;
public:
    Player(int id);
    ~Player();
}

class HumanPlayer : public Player {
public:
    HumanPlayer(int id, string name);
}

我想为 HumanPlayer 创建一个构造函数来设置玩家 ID 和名称,但我似乎不知道如何将 Player::id 设置为 HumanPlayer::id。

这是我计算出来的但是给出了一个错误 “int Player::id'在此上下文中是私有的”

HumanPlayer::HumanPlayer(int id, string name) : Player(id){
    this -> id = id;
    this -> name = name;
}

敬请谅解。

class Player {
private:
    int id;
protected:
    std::string name;
public:

    //Base class constructor, initialize Id.
    Player(int i):id(i)
    {}

    ~Player() {}

    //Test
    int GetId()
    {
        return id;
    }

    std::string GetName()
    {
        return name;
    }
};

class HumanPlayer : public Player {
public:
    HumanPlayer(int i, std::string s) :Player(i) //Pass on Id  base class constructor
    {
        name = s; //Protected variable accessible.
    }
};

void main()
{
    HumanPlayer hPlayer(10, "Test");

    std::cout << hPlayer.GetId() << std::endl;
    std::cout << hPlayer.GetName() << std::endl;
}