[英]Operator equals overloading c++ apparently not working
Can someone explain me why the cout
doesn't get called here?有人可以向我解释为什么
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;
is creating a reference for Test
and initiaizing that.正在为
Test
创建参考并对其进行初始化。 =
operator is not used there. =
运算符不在那里使用。 There are no cout
other than inside operator=
, so cout
won't be called.除了内部
operator=
之外没有cout
,因此不会调用cout
。
Note that注意
Test t3 = t1;
(without &
) will also not call operator=
because this is an initialization of object and a constructor is used for that. (没有
&
)也不会调用operator=
因为这是 object 的初始化并且为此使用了构造函数。
To use operator=
, you should do like要使用
operator=
,你应该这样做
Test t3;
t3 = t1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.