运算符等于重载c++显然不起作用
有人能解释一下为什么cout这里没有被调用吗?
#include <iostream>
using namespace std;
class Test {
public:
int a = 1;
Test &operator=(const Test &other) {
cout << "overloading here" << endl;
return *this;
}
};
int main() {
Test t1;
Test &t3 = t1;
return 0;
}
回答
Test &t3 = t1;
正在创建一个参考Test并启动它。=那里不使用运算符。cout除了 inside没有其他operator=,所以cout不会被调用。
注意
Test t3 = t1;
(without &) 也不会调用,operator=因为这是对象的初始化,并且为此使用了构造函数。
要使用operator=,你应该像
Test t3;
t3 = t1;