gpt4 book ai didi

c++ - 在类方法中修改私有(private)类变量?

转载 作者:太空狗 更新时间:2023-10-29 21:47:45 25 4
gpt4 key购买 nike

这可能是我犯的一个非常基本的错误,但我是 c++ 的新手,所以请不要判断!

基本上,我有两个类如下:

class A{
private:
vector< vector<int> > images;

public:
int f1(int X, int Y);
}

class B{
private:
int x;
int y;

public:
int f2(A var);
}

我希望能够使用定义的变量 A 和 B 调用 B.f2(A),并让 f2() 调用 A.f1(x,y)。到目前为止,所有这些都有效。但是函数 f1 将值分配给 f2() 返回时不存在的 vector “图像”。任何想法为什么?这是代码:

int A::f1(int X, int Y){
// Some stuff to resize images accordingly
images[X][Y] = 4;
return 0;
}

int B::f2(A var){
var.f1(x, y);
return 0;
}

int main(){
A var1;
B var2;

// Stuff to set var2.x, var2.y
var2.f2(var1);

// HERE: var1.images IS UNCHANGED?
}

最佳答案

这是因为您已将A 传递给了。相反,通过引用传递它。

void fn(A& p);
^ << refer to the original object passed as the parameter.

就像现在一样,您的程序会创建 var1拷贝,然后对其进行变异。

当你不想改变参数时,你可以将它作为常量引用传递:

void fn(const A& p);
^^^^^ ^

关于c++ - 在类方法中修改私有(private)类变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12557116/

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