[英]C++, child with both parents having a same ancestor
I'm having trouble with C++ classes and inheritance right now...我现在遇到 C++ 类和 inheritance 的问题...
Let's say we have假设我们有
Class A {
A(string name);
~A();
void func(void);
}
Class B : public A {
B(string name);
~B();
...
}
Class C : public A {
C(string name);
~C();
...
}
Class D : public B, public D {
D(string name);
~D();
...
}
Whenever I create D
, it calls the constructor for B
and the one for C
which results in multiple instances of A
.每当我创建
D
时,它都会调用B
的构造函数和C
的构造函数,这会导致A
的多个实例。 The compiler then says it doesn't know which "func" it should call, the one from B
or the one from C
.然后编译器说它不知道应该调用哪个“函数”,是来自
B
的那个还是来自C
的那个。
I would like to know how to call A
constructor ONLY ONCE and then use it to build B
and C
.我想知道如何只调用
A
构造函数一次,然后用它来构建B
和C
。
I already tried using B::func()
to be able to call func()
but has I must have a cout in the class A builder.我已经尝试使用
B::func()
来调用func()
但我必须在 class A 构建器中有一个 cout。 It results in wrong output.结果是错误的 output。
This is called the diamond inheritance pattern .这称为菱形 inheritance 图案。
In order to avoid having 2 instances of A
in D
, you need to use virtual inheritance .为了避免
A
在D
中有 2 个实例,您需要使用虚拟 inheritance 。
When classes eg B
virtually inherit A
, it means that A
will be present only once in a class derived from those classes.当
B
等类实际上继承A
时,这意味着A
将仅在从这些类派生的 class 中出现一次。
Note: in this case it is the responsibility of the most derived class to initialize the virtual base(s) - as shown below.注意:在这种情况下,最派生的 class 负责初始化虚拟基础 - 如下所示。
The output from the following code demonstrates it:以下代码中的 output 对其进行了演示:
#include <iostream>
#include <string>
class A {
public:
A(std::string const & name) { std::cout << "A::A\n"; };
~A() {};
void func(void);
};
//--------vvvvvvv-----------
class B : virtual public A {
public:
B(std::string const& name) : A(name) { std::cout << "B::B\n"; };
~B() {};
};
//--------vvvvvvv-----------
class C : virtual public A {
public:
C(std::string const& name) : A(name) { std::cout << "C::C\n"; };
~C() {};
};
class D : public B, public C {
public:
//-------------------------------vvvvvvv---------------------------------------------
D(std::string const& name) : A(name), B(name), C(name) { std::cout << "D::D\n"; };
~D() {};
};
int main()
{
D d("aaa");
}
Output: Output:
A::A
B::B
C::C
D::D
Ie A
is present once in D
.即
A
在D
中出现一次。
Note that if you remove the virtual
keyword, the output will be:请注意,如果您删除
virtual
关键字,则 output 将是:
A::A
B::B
A::A
C::C
D::D
Ie A
is present twice in D
(as you observed).即
A
在D
中出现两次(如您所见)。
Some side notes:一些旁注:
using namespace std
- see here Why is "using namespace std;"using namespace std
- 请参阅此处为什么“使用命名空间标准;” considered bad practice? Class
should be class
, missing ;
Class
应该是class
,缺少;
at the end of classes.name
by const &
as demonstrated in my code, to avoid copy.const &
接受name
,如我的代码中所示,以避免复制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.