例子
example 1
注:若一個基類同時派生出兩個派生類,即兩個派生類從同一個基類繼承,那麼系統將為每一個簡歷副本,每個派生類獨立地使用自己的基類副本(比如基類中有屬於自己類的靜態變量等)。
#include
class Person
{
public:
person() {cout<<"Construction of person."<
class Student:public person
{
public:
student() {cout<<"Construction of student."<
class Teacher:public Person
{
public:
Teacher() {cout<<"Construction of teacher."<
int main()
{
Student s;
Teacher t;
}
程序輸出:
Construction of person.
Construction of student.
Construction of person.
Construction of teacher.
Destruction of teacher.
Destruction of person.
Destruction of student.
Destruction of person.
結論:若一個程序中有多個對象,每個對象必須按照順序創建,在創建派生類對象時,調用構造函數的順序為:基類構造-->子對象構造-->派生類構造。析構函數的調用順序嚴格與構造函數相反。在派生類的構造函數中,當基類的構造函數缺省參數時,在派生類構造函數中可以缺省對基類構造函數的調用。
example 2
#include
class Data
{
public:
Data(int x) {Data::x = x; cout<<"Data construction."<
int x;
};
class Base
{
public:
Base(int x):d1(x) {cout<<"Base construction."<
Data d1;
};
class Device:public Base
{
public:
Device(int x):Base(x), d2(x) //參數共用
{cout<<"Device construction."<
Data d2;
};
int main()
{
Device obj(5);
}
程序輸出:
Data construction.
Base construction.
Data construction.
Device construction.
Device destruction.
Data destruction.
Base destruction.
Data destruction.
構造順序分析:調用Base類構造,而Base中含有子對象d1,所以要先調用d1的構造函數再調用Base的構造函數;Base構造函數調用完成之後再調用d2的構造;最後一步是調用派生類的構造。
example 3
class Base
{
public:
Base(int xx = 0):x(xx) //注意沒有分號,等價於普通的構造函數類型
{cout<<"Base construction."<
private:
int x;
};
class Device:public Base
{
public:
Device(itn xx = 0, int yy = 0):Base(xx), y(yy), z(xx+yy)
{cout<<"Device construction."<
{
Base::print();
cout<
private:
int y;
Base z;
};
int main()
{
Device obj1(1), obj2(4, 6);
obj1.print();
obj2.print();
}
程序輸出:
Base construction.
Base construction.
Device construction.
Base construction.
Base construction.
Device construction.
2,0,2
4,6,10
析構略......