提问人:o_yeah 提问时间:11/2/2020 更新时间:11/2/2020 访问量:394
未调用复制赋值 operator=
Copy assignment operator= is not called
问:
为什么在这种情况下不调用重载运算符(operator=)?
#include<iostream>
using namespace std;
class mc{
public:
mc()=default;
mc(mc& that){cout<<1;} //simplified copy constructor
mc& operator=(mc& that){cout<<2; return that;} // simplified copy assignment operator
mc operator=(mc that){cout<<2; return that;} // another simplified copy assignment operator
};
int main(){
mc i; //call default constructor
mc j = i; //Why this line calls j's copy constructor?
//It used "=" symbol, how come copy assignment operator (operator=) is not called?
}
答:
3赞
Ahmed Anter
11/2/2020
#1
主要规则是:
创建新对象时使用复制构造函数。
如果要更改现有对象的值,则使用赋值运算符。
评论
0赞
o_yeah
11/2/2020
谢谢。我明白你的意思。但我想更深入地研究编译器如何处理这种情况。当它在 main 中看到 = 时,首先要做的是查找要调用的 operator= 函数。这是对的吗?
1赞
Ahmed Anter
11/2/2020
编译器检查 var 声明的第一件事,如 int i;并为该对象分配所需的内存,然后调用相应的构造函数。但是当它看到 var i=k;然后,它不是调用构造函数,而是直接调用复制构造函数,而不是调用赋值运算符
下一个:何时调用复制分配运算符?
评论
=
mc j = i;
=
main
operator=
type var=init;
var
type
init
operator=
var = value;
value
void f(int x = 42);