有人能解释一下为什么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;
}
Run Code Online (Sandbox Code Playgroud)
Test &t3 = t1;
Run Code Online (Sandbox Code Playgroud)
正在创建一个参考Test并启动它。=那里不使用运算符。cout除了 inside没有其他operator=,所以cout不会被调用。
注意
Test t3 = t1;
Run Code Online (Sandbox Code Playgroud)
(without &) 也不会调用,operator=因为这是对象的初始化,并且为此使用了构造函数。
要使用operator=,你应该像
Test t3;
t3 = t1;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
78 次 |
| 最近记录: |