在继承中的析构函数主要遵从一下四点规则:
1、首先调用派生类的析构函数(清理派生类的新增成员)
2、如果派生类中有子对象 , 则再调用派生类中子对象的析构函数 , 调用顺序是:在派生类中,先定义后调用。(清理派生类新增的成员对象)
3、再调用普通基类的析构函数(清理从基类继承来的新增成员)
4、最后调用虚基类的析构函数
#include <iostream>
using namespace std;
class base2
{
public:
base2() {}
base2(int i)
{
b = i;
}
~base2() {cout<<"base2"<<endl;}
private:
int b;
};
class base1
{
public:
base1() {}
base1(int i)
{
a = i;
}
~base1() {cout<<"base1"<<endl;}
private:
int a;
};
class base3
{
public:
base3() {};
base3(int i)
{
c = i;
}
~base3() {cout<<"base3"<<endl;}
private:
int c;
};
class derivedclass:public base1
{
public:
derivedclass(int i , int k , int m);
~derivedclass() {cout<<"derivedclass"<<endl;}
private:
int d;
base2 f;
base3 g;
};
derivedclass::derivedclass(int i , int k , int m):base1(k),f(i),g(m)
{
d = m;
}
int main()
{
derivedclass a(1 , 3, 4);
return 0;
}
运行结果: