c++ - 我可以将某些对象的指针保存在向量中,然后用这些指针调用内联函数吗
问题描述
让我们假设我有一个具有某些成员功能的 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 值
解决方案
那是因为您正在存储指向对象副本的指针:
void Game::addPlayer(Player A)
您需要使用参考并存储它:
void Game::addPlayer(Player& A)
否则你会得到一个未定义的行为。
推荐阅读
- r - R错误:{中的错误:任务1失败-“参数长度为零
- javascript - 解析 json 字符串并且 json.stringify 无法正常工作时总是得到一个未定义的值
- wordpress - 在 ACF 字段中保存 WooCommerce OrderData
- spring - 在运行 Spring 之前编辑 application.properties 中的环境变量
- c - 进程的最小页表大小?
- javascript - 如何使命名空间和外部模块在打字稿旧项目中共同存在
- go - 如何找到 rr 和 fifo 的周转时间和响应时间以及有什么区别?
- electron - 无法解析网络工作者中的加密(仅限电子构建)
- ubuntu - 错误:无法初始化 batch_readline - 可能是输入源是目录或块设备 Ubuntu
- laravel - 在 SPA 中设置工作流 Laravel cookie