多继承且有内嵌对象时构造函数的调用顺序

1、调用基类构造函数,调用顺序按照他们被继承时声明的顺序(从左到右)

2、调用成员对象的构造函数,调用顺序按照它们在类中声明的顺序

3、最后调用本类的构造函数

#include <iostream>
using namespace std;
class B1    //基类B1,构造函数有参数
{public:
    B1(int i) {cout<<"constructing B1 "<<i<<endl;}
};
class B2    //基类B2,构造函数有参数
{public:
    B2(int j) {cout<<"constructing B2 "<<j<<endl;}
};
class B3    //基类B3,构造函数无参数
{public:
    B3(){cout<<"constructing B3 *"<<endl;}
};
class C: public B2, public B1, public B3 
{
public:    //派生类的公有成员
    C(int a, int b, int c, int d): 
       B1(a),memberB2(d),memberB1(c),B2(b)  
    {
      cout<<"constructing c *"<<endl; 
    }
private: //派生类的私有对象成员 B1 memberB1; B2 memberB2; B3 memberB3; }; int main() { C obj(1,2,3,4); }

结果:

constructing B2 2
constructing B1 1
constructing B3 *
constructing B1 3
constructing B2 4
constructing B3 *
constructing c *

 

posted @ 2016-04-01 14:31  高傲的monkey  阅读(1166)  评论(0编辑  收藏  举报