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

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

我有这样的代码(所有代码都是作为一个最小的,可复制的示例制作的:]

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

P.S。:Vector2f只是SFML库使用的2D向量。

c++ reference sfml
1个回答
0
投票

实际上,您的代码中的董事会已(正确地)通过引用促销功能传递。您确定函数调用后未更改吗?如果执行此操作,它将显示什么:

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;
};
© www.soinside.com 2019 - 2024. All rights reserved.