gpt4 book ai didi

c++ - 将引用作为函数参数传递不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 12:32:09 26 4
gpt4 key购买 nike

我有这样的代码(都是为最小的、可重现的示例而制作的):

enum class gameState{
Normal,
Special};

class Piece{
public: Vector2i position;
int shape;};

class Board{
public: int array[8][8];
std::vector<Piece> f;
Board() : f(std::vector<Piece>(32)) {}; };

void promotion(int shape, gameState &state, Board &b){
state = gameState::Special;
b.array[b.f[0].position.x][b.f[0].position.y] = shape;
b.f[0].shape = shape;};

然后我尝试在 main 中调用它们:

int main(){
gameState state = gameState::Normal;
Board b;
promotion(1, state, b);
return 0;};

问题是它似乎正确地通过引用传递了 gameState state 对象,它没有修改 Board b 对象,这是不应该发生的。如何通过引用(或指针)正确传递 Board b

附注:Vector2f 只是 SFML 库使用的二维 vector 。

最佳答案

实际上,您代码中的 Board 正在(正确地)通过引用传递给促销功能。你确定它在函数调用后没有改变吗?如果你这样做,它会打印什么:

int main(){
gameState state = gameState::Normal;
Board b;
std::cout << b.array[b.f[0].position.x][b.f[0].position.y] <<std::endl;
promotion(1, state, b);
std::cout << b.array[b.f[0].position.x][b.f[0].position.y] <<std::endl;;
return 0;
};

关于c++ - 将引用作为函数参数传递不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58256764/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com