#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;
}
运行结果:
本文通过两个示例详细解析了C++中派生类构造函数如何调用基类构造函数及其调用顺序,包括基类声明顺序的影响及派生类内部成员对象的初始化流程。
1137

被折叠的 条评论
为什么被折叠?



