【发布时间】:2016-05-26 18:18:17
【问题描述】:
MWE 是
#include <iostream>
using namespace std;
class N {
public:
float x;
N() { x = 0.0; }
N(float a) { x = a; }
//N(N &n) { x = n.x; }
N &operator=(float f) { cout << "########";return *new N(f); }
};
int main() {
N a;
a = 3.0;
cout << a.x;
return 0;
}
我的预期是:它打印出 3,但实际上打印出 0。似乎值没有改变。
那我改成
x = f; return *this;
成功了,为什么?
【问题讨论】:
-
无论您在哪里读到
operator=应该返回对newed 对象的引用,请阅读其他内容 -
*new N(f)作为分配的评估返回。cout << (a = 0.3).x在访问赋值返回的表达式时返回 3.0。
标签: c++ operator-overloading new-operator