我偶然发现了这个代码示例:
#include <iostream>
using namespace std;
class A {
int x;
public:
A() { x = 1; cout << "A"; }
};
class B : virtual public A {
int y;
public:
B() { y = 2; cout << "B"; }
};
class C : virtual public B, virtual public A {
int z;
public:
C() { z = 3; cout <<"C"; }
};
class D : public A, public B, public C {
int t;
public:
D() { t = 4; cout << "D"; }
};
int main()
{
D d;
return 0;
}
这段代码打印出来ABABCD
,我不知道为什么。我以为它会打印A
for D : public A
,然后AB
for D : public B
,然后ABC
for D : public C
,然后D
,但似乎A
只打印了两次。这是如何运作的?