【问题标题】:Modifying private class variables within a class method?在类方法中修改私有类变量?
【发布时间】:2012-09-15 10:41:39
【问题描述】:

这可能是我犯的一个非常基本的错误,但我对 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?
}

【问题讨论】:

    标签: c++ class methods private


    【解决方案1】:

    这是因为您通过 传递了A。而是通过引用传递它。

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 2018-09-01
      • 2012-09-24
      • 1970-01-01
      • 1970-01-01
      • 2017-03-27
      • 2016-05-07
      相关资源
      最近更新 更多