1

我有一个基类,从它派生的类很少。我没有在基类中编写任何复制构造函数,它使用的是默认构造函数。

所以如果我写这段代码:

base* b;
b = new base(*this)

它工作正常,但如果我写这样的东西:

base* b;
b = new derive(*this) 

它给了我一个错误,因为派生类中没有匹配的函数。

我不能将基类的this指针传递给它的派生类复制构造函数来初始化它吗?

4

3 回答 3

3

Derived复制构造函数const Derived &作为它的参数。你不能const Base &用作论据。

您正在尝试执行以下操作:

Derived *d = new Derived();
Base *b = new Base(*d); //ok, since Derived is subclass of Base

Base *b = new Based();
Derived *d = new Derived(*b); //error, since Base in not subclass of Derived

为了构造你需要自己提供这样的构造函数DerivedBase

Derived(const Base &base) {...}
于 2012-07-25T09:58:10.720 回答
0

使用以基类作为参数的版本重载派生构造函数。那应该行得通。

于 2012-07-25T10:01:02.293 回答
0

不,你不能。可能还有其他子类base。如果 class 的复制构造函数derive接受 a const base&,那么您可以将 . 的另一个子类的实例传递给它base。类的复制构造函数derive不知道如何处理这样的对象。

于 2012-07-25T10:01:14.313 回答