[英]copy constructor in derived class
I have a base class and there are few classes being derived from it. 我有一个基类,很少有类来自它。 I have not written any copy constructor in the base class, it is using the default one.
我没有在基类中编写任何复制构造函数,它使用的是默认构造函数。
So if I write this code: 所以,如果我写这个代码:
base* b;
b = new base(*this)
it works fine, but if I write something like this: 它工作正常,但如果我写这样的东西:
base* b;
b = new derive(*this)
it gives me an error for no matching function in the derived class. 它给出了派生类中没有匹配函数的错误。
Can't I pass base class' this
pointer to its derived class copy constructor to get it initialized? 我不能将基类'
this
指针传递给它的派生类复制构造函数来初始化它吗?
Derived
copy constructor takes const Derived &
as it's argument. Derived
拷贝构造函数采用const Derived &
作为它的参数。 You can't use const Base &
as an argument. 您不能使用
const Base &
作为参数。
You are trying to do: 你正在努力:
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
In order to construct Derived
from Base
you need to provide such constructor yourself: 为了构造
Derived
from Base
你需要自己提供这样的构造函数:
Derived(const Base &base) {...}
Overload the derived contructor with a version that takes the base class as parameter. 使用以基类作为参数的版本重载派生的构造函数。 That should work.
这应该工作。
No, you can't. 不,你不能。 There could be other subclasses of
base
. 可能还有其他
base
类。 If the copy constructor of class derive
would accept a const base&
, then you could pass it an instance of another subclass of base
. 如果类的拷贝构造函数
derive
会接受一个const base&
,那么你可以通过它的另一个子类的实例base
。 The copy constructor of class derive
wouldn't know what to do with such an object. 类
derive
的复制构造函数不知道如何处理这样的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.