2012-07-25 36 views
1

我有一个基类,并且从它派生的类很少。我没有在基类中写任何拷贝构造函数,它使用默认的构造函数。派生类中的拷贝构造函数

所以,如果我写这样的代码:

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

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

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

它让我对没有匹配功能的错误在派生类中。

无法将基类'this指针指向其派生类复制构造函数以初始化它?

回答

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) {...} 
+0

感谢您的回答安德鲁,所以要构建Derived(const Base&base){...},我必须首先编写一个基类复制构造函数?其实我尝试添加派生类覆盖版本,正如你所建议的,但现在它抱怨在基类中没有匹配函数:( – Ruchi 2012-07-25 10:18:43

+0

@Ruchi:如果默认的不够用 - 是的,但不要忘记调用基础拷贝构造函数派生初始值设定项列表 – Andrew 2012-07-25 10:20:15

+0

好的,我写了类似于派生派生::派生(const base&b),但它给了我错误:错误:没有匹配的函数调用base :: base(),候选人是base :: base (const base&)和base :: base(some_arg),我不知道什么是错误的,我的意思是为什么erive :: derive(const base&b)试图调用base :: base()?? – Ruchi 2012-07-25 10:34:48

0

过载配版的衍生构造器,是以基地类作为参数。这应该工作。

0

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