c++ - 用户定义复制构造函数时构造函数的行为

标签 c++

我正在尝试理解复制构造函数,请理解我它是如何工作的。

案例一

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 2Case 4 中出现错误?这是因为我创建了用户定义的复制构造函数吗?如果原因是用户定义的复制构造函数,甚至编译器也会提供默认的复制构造函数。像 fruit(fruit &) internally 所以即使这样,编译器提供的程序也可以使用复制构造函数。为什么它不会在 Case 1Case 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/

相关文章:

c++ - 根据 C++17 标准,为什么反向迭代器不是正式的迭代器类别?

c++ - 测试用例 VS ASSERTION 语句

.net - MONO FTP 客户端错误 - 530 - 用户访问被拒绝

c++ - 如何将图像作为资源包含在 C++ 可执行文件中?

c++ - Bison 上下文中使用的 C++ 中的 union

c++ - 在windows中获取当前线程的NUMA Node

c++ - 将 std::any_of、std::all_of、std::none_of 等与 std::map 一起使用

c++ - SFINAE 和可变参数模板类

c++ - 构造函数中的非零默认值

c++ - 在 while 循环中,最后一个逗号分隔的语句是否保证最后运行?