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?
如果未定义构造函数,则编译器将生成默认构造函数,但是,如果您确实定义了构造函数(如副本构造函数),则编译器将不会生成默认构造函数,因此您也需要定义该构造函数。
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. 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).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.