无法将对象存储到数组中? C++

发布于 2024-11-07 19:45:25 字数 545 浏览 0 评论 0原文

我试图做一些简单的事情并将一个对象存储到 C++ 中的数组中,但它一直说我不能使用 = 运算符,而右手操作数属于我的类。这是代码:

class Player {
    string name;
    double points;
    bool wonLastRound;
public:
    Player() {}
    Player(string n)
    {
        name = n;
    }
    const Player &operator=(const Player &);
    void addPoints(double p)
    {
        points += p;
    }
};

这是实例化的代码,

void initPlayers()
{
    for(int i = 0; i < 4; i++)
        players[i] = new Player("Player " + i);
}

我们将不胜感激,我真的需要尽快完成这个项目!

I'm trying to do something simple and store an object into an Array in C++ but it keeps saying that I can't use the = operator with the right hand operand being of my class. Here's the code:

class Player {
    string name;
    double points;
    bool wonLastRound;
public:
    Player() {}
    Player(string n)
    {
        name = n;
    }
    const Player &operator=(const Player &);
    void addPoints(double p)
    {
        points += p;
    }
};

and here's the code to instantiate

void initPlayers()
{
    for(int i = 0; i < 4; i++)
        players[i] = new Player("Player " + i);
}

any help would be appreciated, I really need to get this project finished soon!

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

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

发布评论

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

评论(1

2024-11-14 19:45:26

应该是,

Player& operator = (const Player &);  // remove "const" (it's not mandatory though)

实际问题在于for循环内的赋值。您不必new对象,因为您存储的是值而不是指针。
用法:

players[i] = Player("Player " + i);  // no need to do "new"

It should be,

Player& operator = (const Player &);  // remove "const" (it's not mandatory though)

Actual problem lies in assignment inside for loop. You don't have to new the objects, as you are storing value and not the pointer.
Usage:

players[i] = Player("Player " + i);  // no need to do "new"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文