C++中派生类析构函数实例

来源:互联网 发布:百度软件中心 编辑:程序博客网 时间:2024/06/11 02:30

派生类析构函数的执行次序和构造函数正好相反,顺序如下:

首先,派生类新增的普通成员进行处理,然后对派生类新增的对象成员进析构处理,最后对所有从基类继承来的成员进行处理。

这些工作分别是执行

1。 派生类析构函数。

2。 调用派生类对象成员所在的类的析构函数。

3。调用基类析构函数

--------------------------------------------------

/*
 * File:   main.cpp
 * Author: yubao
 *
 * Created on May 31, 2009, 8:12 AM
 */

#include <iostream>
using namespace std;
class B1
{
public :
    B1(int i){cout<<"constructing B1   "<<i<<endl;} //基类构造函数,有参数
    ~B1(){cout<<"destructing B1"<<endl;}
};
class B2
{
public :
    B2(int j){ cout<<"constrcuting B2   "<<j<<endl;}//基类构造函数,有参数
    ~B2(){cout<<"destructing B2"<<endl;}
};
class B3
{
public :
    B3(){cout<<"constructing B3 * "<<endl;}//基类构造函数,无参数
    ~B3(){cout<<"destructing B3"<<endl;}
};
class C:public B2, public B1, public B3
{
public:
    C(int a,int b,int c,int d):B1(a),memberB2(d),memberB1(c),B2(b){}//注意派生类的基类声明顺序
private :
    B1 memberB1;//注意内迁对象的声明顺序
    B2 memberB2;
    B3 memberB3;
};


/*
 *
 */
int main(int argc, char** argv) {
    C obj(1,2,3,4);
    return 0;
}