繁体   English   中英

运算符等于重载 c++ 显然不起作用

[英]Operator equals overloading c++ apparently not working

有人可以向我解释为什么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创建参考并对其进行初始化。 =运算符不在那里使用。 除了内部operator=之外没有cout ,因此不会调用cout

注意

    Test t3 = t1;

(没有& )也不会调用operator=因为这是 object 的初始化并且为此使用了构造函数。

要使用operator= ,你应该这样做

    Test t3;
    t3 = t1;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM