将引用作为函数参数传递不起作用
Passing references as function arguments doesn't work
我有这样的代码(都是为最小的、可重现的示例而制作的):
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 库使用的二维向量。
实际上,您代码中的 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;
};
我有这样的代码(都是为最小的、可重现的示例而制作的):
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 库使用的二维向量。
实际上,您代码中的 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;
};