开发者

can't store an object into array? C++

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 projec开发者_如何学运维t finished soon!


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"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜