【发布时间】: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