Pra*_*ngh 1 c++ copy-constructor assignment-operator
我的问题是最后的陈述,即之前的陈述 return 0;
当我们尝试将int值分配给对象时,为什么要调用参数化构造函数.
我的代码:
#include<iostream>
using namespace std;
class Test {
private:
int i;
public:
Test(int s=0):i(s) {
cout<<"param ctor: "<<i<<endl;
}
};
int main()
{
Test a; //param ctor called
Test b(5); //param ctor called
//b(a); //error as we have not implemented copy ctor
b=a; //compiler provided assignment opr. called
b=100; //why param ctor called for this.??
return 0;
}
Run Code Online (Sandbox Code Playgroud)
OUTPUT:
param ctor: 0
param ctor: 5
param ctor: 100
Run Code Online (Sandbox Code Playgroud)
原因很简单:每个类X都有一个复制构造函数(一个构造函数X)和一个复制赋值运算符(一个赋值运算符X).如果您不自己声明这些,则编译器会隐式声明它们.在某些情况下,它们被定义为已删除(这意味着使用它们是错误的),但它们始终存在.
所以当你这样做时:
b = 100;
Run Code Online (Sandbox Code Playgroud)
它有效地转化为:
b.operator=(100)
Run Code Online (Sandbox Code Playgroud)
并operator=搜索最佳匹配重载.实际上只有一个重载:隐式声明的复制赋值运算符Test& Test::operator=(const Test &),因此编译器会检查它是否可以将参数转换100为赋值运算符的参数类型const Test &.事实证明,由于转换构造函数Test::Test(int),它可以最终调用.
如果要禁用此类行为,可以将构造函数标记为explicit.这将阻止它用于隐式转换,例如转换100为赋值运算符参数类型的转换.
| 归档时间: |
|
| 查看次数: |
67 次 |
| 最近记录: |