多继承
按照继承声明列表的顺序(笔者YY,即冒号后面的声明顺序)进行构造。
对象成员
按照在类中声明的顺序进行构造
#include <iostream>
#include <string>
using std::string;
using std::cout;
using std::endl;
class Base{
public :
Base(int a, string s = "Default in Base"){
cout << a << ":" << s << endl;
}
};
class Base1 :virtual public Base{
public:
Base1(int i, string s = "default in Base1", int j = 0) :Base(j, "Base of Base1"){
cout << i << ":" << s << endl;
}
};
class Base2 : public virtual Base{
public:
Base2(int i, string s = "default in Base2", int j = 0) : Base(j, "Base of Base2"){
cout << i << ":" << s << endl;
}
};
class Son : public Base2, public Base1{
public:
Son(int a, int b, int c, int d)
:Base1(a, "Base1 from Son"), Base2(b, "Base2 From Son"), b1(c, "Object of Base1"),
b2(d, "Object of Base2"), Base(a, "Base from Son"){
}
private:
Base2 b2;
Base1 b1;
};
int main()
{
Son s(1, 2, 3, 4);
return 0;
}
结果如下:
继承与组合
对于拥有对象成员的类来说,构造顺序是:先构造对象成员,再构造自己,构造对象成员的顺序按照类中声明的顺序,示例如下:
#include <iostream>
#include <string>
using namespace std;
class A{
public:
A()
{
cout << "A's ctor" << endl;
}
};
class B
{
public:
B()
{
cout << "B's ctor" << endl;
}
};
class C{
public:
C()
{
cout << "C's ctor" << endl;
}
B b;
A a;
};
int main(int argc, char** argv)
{
C c;
return 0;
}
运行后的结果如下: