为什么赋值操作调用的是单参构造函数?
- C/C++ code
class WhoWillBeCall{public: WhoWillBeCall() { printf("default param Constructor\n"); m_i=1; }; ~WhoWillBeCall(){}; WhoWillBeCall(int i) { printf("single param Constructor\n"); }; WhoWillBeCall &operator=(int &ref) { printf("operator = "); return *this; } int m_i;};- C/C++ code
WhoWillBeCall test;test = 1;
结果是
- C/C++ code
default param Constructorsingle param Constructor
把
- C/C++ code
WhoWillBeCall &operator=(int &ref)
改为
- C/C++ code
WhoWillBeCall &operator=(const int &ref)
则是
- C/C++ code
default param Constructoroperator =
这个...什么原理?
const int &ref 能指代任何的值?
而int ref只能指代int类型的变量?
记得primer里提过
const类型的引用可以指向任何的值
因为编译器会为其生成中间代码
const int& ref = 100.12;
{
int temp = 100.12;
const int&ref = temp;
}
不过忘了这么做的含义了。
[解决办法]
const int &ref能够接受右值,而int &ref只能接受左值;
WhoWillBeCall test;
test = 1;
1是右值,在const int &ref时,以上语句刚好对应了重载的=;而int &ref时找不到对应的=运算,以上语句就被编译器解释成为了拷贝构造函数的调用进行初始化。