警告:应在复制构造函数中显式初始化基类“A” [英] warning: base class ‘A’ should be explicitly initialized in the copy constructor
问题描述
我有以下类结构:
class A{
A(){}
A(const A& src){}
};
class B : virtual A {
B():A(){}
B(const B& src):A(src){}
};
class C : virtual A {
C():A(){}
C(const C& src):A(src){}
};
class D : virtual B, virtual C {
D():B(),C(){}
D(const D& src):B(src),C(src){}
};
这给了我警告:
在复制构造函数'D'中:
In copy constructor ‘D’:
警告:基类'A'应在副本
构造函数中显式初始化
warning: base class ‘A’ should be explicitly initialized in the copy constructor
我不介意。
D的Copy -Constructor调用B的 copy-ctor
,调用 copy-ctor
A.
为什么要我在D中拨打A的 copy-ctor
?
Which I dont unterstand.
The Copy -Constructor of D calls the copy-ctor
of B which calls the copy-ctor
of A.
Why does it want me to call the copy-ctor
of A in D?
如果我这样做,A的 copy-ctor
是否会被调用两次?一旦从B调用并且从D调用一次。
If I would do so, wouldnt the copy-ctor
of A be called twice? Once called from B and once called from D.
对此的任何输入都非常感激。
Any input on this is much appreciated.
推荐答案
现在我已经确认我是对的,B使用虚拟继承来从A派生。
Now I have confirmed that I was right, B used virtual inheritence to derive from A.
当发生这种情况时,派生程度最高的类是负责构建基类。这允许多重继承钻石。
When that happens, the most derived class is responsible for constructing the base class. This allows the multiple inheritence diamond.
======== A ============
^ ^
B C
\ /
\ /
\ /
\ /
D
D来自B和C,两者都来自A所以D将继承A的2个副本,一个来自B和一个来自C。
D derives from B and C and both derive from A so D would inherit 2 copies of A, one from B and one from C.
如果B1和B2都使用虚拟继承从A派生,那么最终的类必须初始化基类,即A,从而确保只有一次实例。
If B1 and B2 both use virtual inheritence to derive from A, then the final class must initialize the base class, i.e. A, thus ensuring just once instance.
这就是你收到错误信息的原因。
This is why you got the error message.
这篇关于警告:应在复制构造函数中显式初始化基类“A”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!