我用虚拟继承编写了这个程序,我有几个问题。
#include<iostream>
using namespace std;
class B1
{
public:
B1()
{
cout << "In B1 constructor\n";
}
};
class V1 : public B1
{
public:
V1()
{
cout << "In V1 constructor\n";
}
};
class D1 : virtual public V1
{
public:
D1()
{
cout << "In D1 constructor\n";
}
};
class B2
{
public:
B2()
{
cout << "In B2 constructor\n";
}
};
class B3 {
public:
B3()
{
cout << "In B3 constructor\n";
}
};
class V2 : public B1, public B2
{
public:
V2()
{
cout << "In V2 constructor\n";
}
};
class D2 : public B3, virtual public V2
{
public:
D2()
{
cout << "In D2 constructor\n";
}
};
class X : public D1, virtual public D2
{
public:
X()
{
cout << "In X constructor\n";
}
};
int main()
{
X x;
return 0;
}
程序的输出:
In B1 constructor
In V1 constructor
In B1 constructor
In B2 constructor
In V2 constructor
In B3 constructor
In D2 constructor
In D1 constructor
In X constructor
我期望这样的输出:
In B1 constructor
In B2 constructor
In V2 constructor
In B2 constructor
In D2 constructor
In B1 constructor
In V1 constructor
In D1 constructor
In X constructor
在先构造一个虚拟基类的对象,再构造另一个基类对象的基础上。有人可以解释这种行为吗?