修改类方法中的私有类变量


这可能是

我犯的一个非常基本的错误,但我对 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() 返回时,这些值不存在。知道为什么吗?代码如下:

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的副本

当您不想改变参数时,可以将其作为 const 引用传递:

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

最新更新