C++语言程序设计

下面我们举个例子来说明构造函数和析构函数的调用顺序。

| 例11-2

#include "iostream.h"
#define CLASS(ID) class ID{\
public:\
ID(int) {cout<<#ID<<" created"<<endl;}\
~ID() {cout<<#ID<<" destroyed"<<endl;}\
};
CLASS(base);
CLASS(member1);
CLASS(member2);
CLASS(member3);
CLASS(member4);

class derived1:public base
{
member1 mem1;
member2 mem2;
public:
derived1(int i) :mem2(i), mem1(i) ,base(i){
cout<<"derived1 created"<<endl;
}
~derived1() {
cout<<"derived1 destroyed"<<endl;
}
};

class derived2 : public derived1
{
member3 mem3;
member4 mem4;
public:
derived2(int i) :derived1(i), mem3(i), mem4(i) {
cout<<"derived2 created"<<endl;
}
~derived2() {
cout<<"derived2 destroyed"<<endl;
}
};

void main()
{
derived2 d(1);
}
在程序中，我们用下面的语句定义类：
#define CLASS(ID) class ID{\
public:\
ID(int) {cout<<#ID<<" created"<<endl;}\
~ID() {cout<<#ID<<" destroyed"<<endl;}\
};

CLASS（base）；
实际上就是：
class base{
public:
base(int) {cout<<"base"<<" created"<<endl; }
~base() {cout<<"base"<<" destroyed"<<endl; }
};

程序运行结果为：
base created
member1 created
member2 created
derived1 created
member3 created
member4 created
derived2 created
derived2 destroyed
member4 destroyed
member3 destroyed
derived1 destroyed
member2 destroyed
member1 destroyed
base destroyed
除了构造函数和析构函数不能被继承外，operater =() 也不能被继承，因为它完成和构造函数类似的工作。