#include <iostream>
using namespace std;
class Base
{
public:
Base(int i) { cout << i; }
~Base () { }
};
class Base1: virtual public Base
{
public:
Base1(int i, int j=0) : Base(j) { cout << i; }
~Base1() {}
};
class Base2: virtual public Base
{
public:
Base2(int i, int j=0) : Base(j) { cout << i; }
~Base2() {}
};
class Derived : public Base2, public Base1
{
public:
Derived(int a, int b, int c, int d) : mem1(a), mem2(b), Base1(c),
Base2(d), Base(a)
{ cout << b; }
private:
Base2 mem2;
Base1 mem1;
};
void main() { Derived objD (1, 2, 3, 4); }
void main() { Derived objD (1, 2, 3, 4); }
建立Derived类对象objD(1, 2, 3, 4),首先调用构造函数Derived(int a, int b, int c, int d) : mem1(a), mem2(b), Base1©, Base2(d), Base(a) { cout << b; }
在构造函数Derived中先调用虚基类Base的构造函数,即Base(a),将a的值1传给i,(Base(int i) { cout << i;)输出i值为1
然后根据声明顺序(class Derived : public Base2, public Base1 )Base2在前,接着调用Base2(d),将d的值传给i,(Base2(int i, int j=0) : Base(j) { cout << i; })输出i值为4,由于Base为虚基类,只有最远端派生类构造函数Derived才能调用虚基类的构造函数,该派生类的其他基类对虚基类构造函数的调用被忽略,所以系统不会做 : Base(j)
再调用Base1©, 将c的值传给i,(Base1(int i, int j=0) : Base(j) { cout << i; }),输出i值为3,同理系统不做: Base(j)
然后根据对象成员声明顺序(Base2 mem2; Base1 mem1;)先做mem2(b), 即调用构造函数Base2(int i, int j=0) : Base(j) { cout << i; },在Base2构造函数中需要先调用Base构造函数,把j=0传值给i,(Base(int i) { cout << i;)输出i值为0,再将b=2的值传给构造函数Base2中的i,输出i值为2
接着做mem1(a),同mem2(b),调用Base1构造函数时先调用Base构造函数,输出i值为0,再将,a=1的值传给构造函数Base1中的i,输出i值为1
最后做构造函数Derived中的{ cout << b; },输出b值为2
结果:14302012`