【问题标题】:C++ class variable not changes after assignmentC++ 类变量在赋值后不会改变
【发布时间】:2021-05-11 12:30:39
【问题描述】:

我有两个类,一个是另一个的私有变量。 私有成员有一个基类,其中有一个变量作为私有成员。 代码如下:

#include <iostream>

class Base {
    public:
  Base(): _p(5) {
      
  }
    
  void setP(int p) {
      _p = p;
  }
  
  int p() const {
      return _p;
  }
private:
  int _p = 0;
};

class Test:  public Base {
    public:
  Test(): Base() {
  }
  
  Test operator=(const Test & self) {
      Test cloned;
      cloned.setP(self.p());
      return cloned;
  }
};

class Test2:  public Base {
    public:
  Test2() {
  }
  
  Test2 operator=(const Test2 & self) {
      Test2 cloned;
      cloned.setTest(self.test());
      return cloned;
  }
  
  Test test() const { return _test; }
  void setTest(const Test & test) { _test = test; }
  
  private:
  Test _test;
};

int main()
{
    Test test;
    test.setP(500);
    
    Test2 newTest;
    newTest.setTest(test);
  
    Test2 newTest2 = newTest;
    std::cout << "p is " << newTest.test().p() << std::endl;
    std::cout << "p2 is " << newTest2.test().p() << std::endl;
}

我检查了代码洞察并看到了一些 operator= 和一些复制构造函数,但我无法弄清楚这是怎么发生的..

当我运行这个程序时,我希望输出是这样的:

p is 500                                                                                                          
p is 500

但我明白了:

p is 5                                                                                                               
p is 5

【问题讨论】:

  • Test 的赋值运算符实际上并没有赋值 - 也就是说,它使赋值的左侧保持不变。因此,Test2::setTest 中的 _test = test; 是无操作的。
  • 赋值运算符应该修改*this,而不是返回一个新对象。
  • 是的@IgorTandetnik,谢谢你提到......
  • @molbdnilo 你是对的,谢谢。我犯了一个愚蠢的错误错误......

标签: c++ class polymorphism operator-overloading


【解决方案1】:

问题在于您的operator=。您创建一个临时的 Test 并对其进行修改,但您不修改 this 对象。正确的实现是:

 Test& operator=(const Test& rhs) {
     setP(rhs.p());
     return *this;
 }

还请注意,operator= 返回引用 Test&amp;,而不是 Test。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多