如何从派生类参数设置基本变量

发布于 2025-02-01 04:22:50 字数 528 浏览 3 评论 0原文

我有班级和人类玩家。人类玩家源自玩家。

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

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

我想为人类游戏制作一个构造函数,设置播放器ID和名称,但我似乎不知道如何将player :: ID设置为HumanPlayer :: ID。

这是我解决的问题,但给出了一个错误 “ int player :: id'在此上下文中是私人的”

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

I have the classes Player and HumanPlayer. HumanPlayer is derived from Player.

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

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

I want to make a constructor for HumanPlayer the set the Player id and name but I don't seem to figure out how to set Player::id to the HumanPlayer::id.

This is what I have worked out but gives an error
"int Player::id' is private within this context"

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情归归情 2025-02-08 04:22:50

为了理解。

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;
}

For your understanding.

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文