#include <iostream>
using namespace std;
class A
{
public:
A ()
{
cout<<"A 构造 "<<endl;
}
virtual ~A() // 定义虚析构函数 导致原来析构顺序发生变化
{
cout<<"A 析构 "<<endl;
} };
class B : public A
{
public:
B ()
{
cout<<"B 构造 "<<endl;
}
~B ()
{
cout<<"B 析构 "<<endl;
} };
class C : public B
{
public :
~C ()
{
cout<<"C 析构 "<<endl;
} C ()
{
cout<<"C 构造 "<<endl;
}
};
int main(int argc, char *argv[])
{
B *b=new C; //由C的构造函数来创建的对象指针b,这一步会说明析构的b的范围最深到c
delete b;
return ;
}
输出结果:
说明:上面的例子对析构A或者对析构B其中一个或者两个采用虚函数,都会是析构顺序从最深的子类,这个最深由创建对象时候确定,如果
#include <iostream>
using namespace std;
class A
{
public:
A ()
{
cout<<"A 构造 "<<endl;
}
virtual ~A()
{
cout<<"A 析构 "<<endl;
} };
class B : public A
{
public:
B ()
{
cout<<"B 构造 "<<endl;
}
~B ()
{
cout<<"B 析构 "<<endl;
} };
class C : public B
{
public :
~C ()
{
cout<<"C 析构 "<<endl;
} C ()
{
cout<<"C 构造 "<<endl;
}
};
class D : public C
{
public :
~D ()
{
cout<<"D 析构 "<<endl;
} D ()
{
cout<<"D 构造 "<<endl;
}
};
int main(int argc, char *argv[])
{
B *b=new C;
delete b;
return ;
}
那么输出结果跟上面的一样