accessor 函数和 mutator 函数可以一起使用吗?

问题描述 投票:0回答:0

(编辑:将

Group
更改为
Groups

我有两个类,Player 和 PlayerList

玩家:

class Player {
    private:
        char* name;
        int elo;
        int score;

    public:
        Player(const char* const name, const int elo);
        ~Player();

        // The accessor, mutator and print functions are given
        int getELO() const { return elo; }
        int getScore() const { return score; }

        void addScore(const int points) { score += points; }

        void print() const {
            std::cout << name << " (" << elo << ")";
        }
};

玩家列表:

class PlayerList {
    private:
        int numPlayers;
        Player** players;

    public:
        PlayerList();
        PlayerList(const PlayerList& list);
        ~PlayerList();

        // The following accessor functions are given
        int getNumPlayers() const { return numPlayers; }
        Player* getPlayer(const int index) const { return players[index]; }

        void addPlayer(Player* const player);
        void sort();
        PlayerList* splice(const int startIndex, const int endIndex) const;
};

在另一个类中,我有一个名为

Groups
的 PlayerList 数组:

PlayerList* Groups = new PlayerList [some_integer_not_important_to_question];

当我尝试使用

addScore
函数时,我的代码就停在那个点上。 我这样做是这样的:

Groups[0].getPlayer(Groups[0].getNumPlayers() - 1)->print(); //This works
Groups[0].getPlayer(Groups[0].getNumPlayers() - 1)->addScore(2); //This doesn't work

没有错误出现,我的代码只是在那一点停止,然后在一段时间后终止。 错误是什么?我不能同时执行 getPlayer(访问器)和 addScore(修改器)吗?

c++ arrays class accessor mutators
© www.soinside.com 2019 - 2024. All rights reserved.