簡體   English   中英

不能將對象存儲到數組中? C ++

[英]can't store an object into array? C++

我正在嘗試做一些簡單的事情,然后將對象存儲到C ++中的Array中,但一直說我不能將=運算符與我的類的右操作數一起使用。 這是代碼:

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

任何幫助將不勝感激,我真的需要盡快完成這個項目!

它應該是,

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

實際問題在於 for循環內for 賦值 您不必new對象,因為您存儲的是值而不是指針。 用法:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM