为什么复制构造函数会调用其他类?默认构造函数?
我想知道为什么会出现这样的错误。
no matching function for call to 'Foo::Foo()'
在复制构造函数的代码中?假设 Foo 只是一个具有普通字段的对象(没有动态分配的内存等),并且它定义的唯一构造函数是一个带有一个参数的构造函数。
我什至不知道需要考虑构造函数。如果代码显示类似
bar = thing.bar; //
并且 bar 是 Foo 类型,并且具有上述规范,那么它不应该只生成一个浅拷贝并使用它来完成吗?为什么需要调用默认构造函数?
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.
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? Why does a default constructor need to be invoked?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
听起来您已经定义了复制构造函数,而没有定义任何其他构造函数。
一旦显式声明构造函数,编译器就不再为您提供默认构造函数。因此,您不再有一种机制来首先构造该类的对象(因此无法复制它)。
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).
如果,正如你所说,你正在做“
大概是在类的复制构造函数的 body 中的事情 - 所以
bar
字段会使用其类的默认构造函数进行初始化首先,然后使用该类的赋值运算符来执行此语句。如果bar
的类只有一个复制构造函数,没有默认构造函数,则需要添加一个bar(thing.bar)。
子句 before 类的复制构造函数打开{
并删除该赋值(无论如何通常都是一个好主意,但在“无默认构造函数”条件下是强制性的)。If, as you say, you're doing "something like
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. Ifbar
's class only has a copy ctor, no default ctor, you'll need to add abar(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).如果您没有定义构造函数,编译器将生成默认构造函数,但是如果您定义了构造函数(如复制构造函数),编译器将不会生成默认构造函数默认构造函数,因此您也需要定义该构造函数。
If you don't define a constructor, the compiler will generate a default constructor, however if you do define a constructor (Like a copy constructor) the compiler won't generate the default constructor, so you need to define that constructor too.