[英]Why does copy constructor call other class' default constructor?
I was wondering why an error like this would occur. 我想知道为什么会发生这样的错误。
no matching function for call to 'Foo::Foo()'
in code for a copy constructor? 在代码中的复制构造函数? Assume Foo is just an object with normal fields ( no dynamically allocated memory, etc. ), and the only constructor it has defined is a constructor that takes one argument.
假设Foo只是具有普通字段的对象(没有动态分配的内存等),并且它定义的唯一构造函数是采用一个参数的构造函数。
I didn't even know the constructor needed to be considered though. 我什至不知道需要考虑构造函数。 If the code says something like
如果代码显示类似
bar = thing.bar; //
and bar is of Foo type, with the specifications described above, shouldn't it just generate a shallow copy and be done with it? 并且bar是Foo类型,具有上述规格,难道它不只是生成一个浅表副本并用它完成吗? Why does a default constructor need to be invoked?
为什么需要调用默认构造函数?
如果未定义构造函数,则编译器将生成默认构造函数,但是,如果您确实定义了构造函数(如副本构造函数),则编译器将不会生成默认构造函数,因此您也需要定义该构造函数。
It sounds like you've defined the copy constructor without defining any other constructor. 听起来您已经定义了复制构造函数而未定义任何其他构造函数。
Once you declare an constructor explicitly, the compiler no longer provides a default constructor for you. 明确声明构造函数后,编译器将不再为您提供默认的构造函数。 Consequently, you no longer have a mechanism to construct an object of the class in the first place (and therefore wouldn't be able to copy it).
因此,首先您将不再具有构造该类的对象的机制(因此将无法复制该对象)。
If, as you say, you're doing "something like 如您所说,如果您正在做“
bar = thing.bar;
it's presumably in the body of your class's copy ctor -- so the bar
field gets initialized with its class's default ctor first, then uses that class's assignment operator for this statement. 它大概位于类的副本ctor的主体中-因此,首先使用其类的默认ctor初始化
bar
字段,然后将该类的赋值运算符用于此语句。 If bar
's class only has a copy ctor, no default ctor, you'll need to add a bar(thing.bar)
clause before your class's copy ctor opening {
and remove that assignment (generally a good idea anyway, but mandatory under the "no default ctor" condition). 如果
bar
的类仅具有复制ctor,没有默认ctor,则需要在类的复制ctor开头{
之前添加bar(thing.bar)
子句, 然后删除该赋值(无论如何通常是一个好主意,但在“没有默认ctor”条件)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.