首页 > 解决方案 > 我可以将某些对象的指针保存在向量中,然后用这些指针调用内联函数吗

问题描述

让我们假设我有一个具有某些成员功能的 Player 类。其中之一使用 this 关键字返回对象的指针。Player* getPlayer() { return this;};

class Player
{
public:

    Player(int id, string name, int score = 0) : pId(id), pName(name), pScore(score) { };
    void rollDice();

    int getId() { return pId; }
    int getScore() { return pScore; }
    string getName() { return pName; }
    Player* getPlayer() { return this;};
private:
    int pId;
    std::string pName;
    int pScore;
    unsigned char playerDiceRolled;
    Dice mDice;
};

我还有一个名为 Game 的类,它使用一个函数将任何玩家的信息保存在不同的向量中。其中一个向量保存了对象向量 playerList 的指针;

class Game
{
public:


    void Winer();
    void addPlayer(Player A) ;
    void updateScore();
    vector<Player*> playerList;
    vector<int> idList;
    vector<string> nameList;
    vector<size_t> scoreList;

};

void Game::addPlayer(Player A)
{

    this->playerList.push_back(A.getPlayer());
    this->idList.push_back(A.getId());
    this->nameList.push_back(A.getName());
    this->scoreList.push_back(A.getScore());

}

我的问题是我可以从该向量中取出指针并使用它来调用该类的函数并返回赖特值。

我试过了,但它不起作用

我可以看到 Player 的其他值已正确保存,但是当我使用指针调用函数以获取值时,它返回 null。例如

int main()
{
    Game Game1;
    Player A(0, "Player1");
    Player B(1, "Player2");
    Game1.addPlayer(A);

    Game1.addPlayer(B);

    cout << "Name is:" << Game1.nameList[1] << "\n";



    cout << "Name is:" << Game1.playerList[1]->getName() << "\n";






    return 0;

}

cout 为 Game1.nameList[1] 提供玩家的赖特名称,但为 Game1.playerList[1]->getName() 提供 NULL 值

标签: c++

解决方案


那是因为您正在存储指向对象副本的指针:

void Game::addPlayer(Player A)

您需要使用参考并存储它:

void Game::addPlayer(Player& A)

否则你会得到一个未定义的行为。


推荐阅读