派生類的構造函數及其對象的初始化

#include <iostream>
using namespace std;

class Base1
{
	int d1;
public:
	Base1(int i)
	{
		d1 = i;
		cout<<"constructing Base1: "<<d1<<endl;
	}
};

class Base2
{
	int d2;
public:
	Base2(int j)
	{
		d2 = j;
		cout<<"constructing Base2: "<<d2<<endl;
	}
};

class Base3
{
	int d3;
public:
	Base3(int k=0)
	{
		d3 = k;
		cout<<"constructing Base3: "<<d3<<endl;
	}
};

class Derived:public Base3, public Base1, public Base2
{
	int d4;
	Base1 memberOBJ1;
	Base3 memberOBJ3;
	Base2 memberOBJ2;
public:
	Derived(int a, int b, int c, int d, int e):memberOBJ2(d), memberOBJ3(b), memberOBJ1(c), Base2(a), Base1(b)
	{
		d4 = e;
		cout<<"constructing Derived: "<<d4<<endl;
	}
};

void main()
{
	Derived obj(1,2,3,4,5);
	while(1);
}
派生類Derived由三個基類Base3,Base1和Base2公有派生,而且該派生類中還含有三個不同基類的類對象memberObj1,memberObj3和memberObj2作爲其數據成員。在這種情況下,派生類的構造函數要負責對其基類數據成員,對其所含對象成員的數據成員以及該派生類新增的其他特有數據成員一塊進行初始化(均通過處於派生類構造函數體前的成員初始化符表來指定完成)。而且總按照如下的一般次序來進行這種初始化:先父母(基類),並嚴格按照基類名的說明順序依次去調用基類構造函數(注意:此處基類的說明順序爲class Derived:public Base3, public Base1, public Base2中的順序,即先基類3,再1,再2);再對象(對象成員),並嚴格按照各對象的說明順序
memberObj1memberObj3memberObj2依次去調用基類構造函數(注意:此處對象成員的說明順序爲派生類構造函數中的順序:
	Base1 memberOBJ1;
	Base3 memberOBJ3;
	Base2 memberOBJ2;

);後自己(本派生類中的構造函數)。

注意: 成員初始化符表中的書寫順序可以與上述的初始化執行次序不相同。

[輸出結果]
 constructing Base3 0
 constructing Base1 2
 constructing Base2 1
 constructing Base1 3
 constructing Base3 2
 constructing Base2 4
 constructing Derived 5

在進行析構時,系統按照構造的相反順序進行工作!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章