您的位置:首页 > 其它

多重继承中派生类的构造函数和析构函数

2016-04-28 09:19 281 查看
#include<iostream>
using namespace std;
class Base1
{
public:
Base1(int i)
{
cout<<"Constructing Base1 "<<i<<endl;
}
};
class Base2
{
public:
Base2(int j)
{
cout<<"Constructing Base2 "<<j<<endl;
}
};
class Base3
{
public:
Base3()
{
cout<<"Constructing Base3 *"<<endl;
}
};
class Derived:public Base1,public Base2,public Base3
{
public:
Derived(int a,int b,int c,int d):Base1(a),Base2(b),number1(c),number2(d){}
private:
Base1 number1;
Base2 number2;
Base3 number3;
};
int main()
{
Derived obj(1,2,3,4);
return 0;
}

运行结果:



心得:

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

2、对本类成员初始化列表中的基本类型成员和对象成员进行初始化,初始化的顺序按照他们在类中声明的顺序,对象成员初始化是自动调用对象所属类的构造函数完成。

3、执行派生类的构造函数体的内容。

对比:

#include<iostream>
using namespace std;
class Base1
{
public:
Base1(int i)
{
cout<<"Constructing Base1 "<<i<<endl;
}
};
class Base2
{
public:
Base2(int j)
{
cout<<"Constructing Base2 "<<j<<endl;
}
};
class Base3
{
public:
Base3()
{
cout<<"Constructing Base3 *"<<endl;
}
};
class Derived:public Base2,public Base1,public Base3
{
public:
Derived(int a,int b,int c,int d):Base1(a),Base2(b),number1(c),number2(d){}
private:
Base1 number1;
Base2 number2;
Base3 number3;
};
int main()
{
Derived obj(1,2,3,4);
return 0;
}


运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: