我正在尝试理解复制构造函数,请理解我它是如何工作的。
案例一
class fruit{
public: int i;
fruit(int j){
i = j;
}
};
int main(){
fruit f1 = fruit(2); // works fine when no user defined copy constructor
return 0;
}
案例二
class fruit{
public: int i;
fruit(fruit &f){
i = f.i + 1;
}
fruit(int j){
i = j;
}
};
int main(){
fruit f1 = fruit(2); // error no matching call fruit::fruit(fruit) why?
return 0;
}
案例三
class fruit{
public: int i;
fruit(){
i = 0;
}
};
int main(){
fruit f2;
fruit f1 = fruit(f2); // works fine when no user defined copy constructor
return 0;
}
案例4
class fruit{
public: int i;
fruit(){
i = 0;
}
fruit(fruit &f){
i = f.i + 1;
}
};
int main(){
fruit f2;
fruit f1 = fruit(f2); // error no matching call fruit::fruit(fruit)
return 0;
}
Technically 'fruit(f2)' must be valid because
f2 can be passed by reference to fruit(fruit &f). right? but why error?
为什么我在 Case 2
和 Case 4
中出现错误?这是因为我创建了用户定义的复制构造函数吗?如果原因是用户定义的复制构造函数,甚至编译器也会提供默认的复制构造函数。像 fruit(fruit &)
internally 所以即使这样,编译器提供的程序也可以使用复制构造函数。为什么它不会在 Case 1
和 Case 3
我知道当用户定义复制构造函数时,所有构造函数都被 =
阻止。 =
只能调用复制构造函数。但是一个类必须有一个复制构造函数,可以由用户或编译器创建。如果它是由编译器提供的,那么它也必须引发错误。但它不这样做为什么?
最佳答案
这不是与复制构造函数相关的问题;非 const
左值引用不能绑定(bind)到临时对象。
将编译以下代码:
fruit f1;
fruit f2(f1);
因为 f1
传入的时候不是临时的。
尽管如此,您还是希望临时对象能够工作,所以像这样编写您的复制构造函数:
fruit(const fruit& f) {
i = f.i + 1;
}
你的案例 1 和 3 成功了,因为编译器能够生成它自己的“默认”复制构造函数已经看到你没有提供一个,它 - 与你不同 - 它做得正确。 :-)
关于c++ - 用户定义复制构造函数时构造函数的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26786726/