一,如果析构函数不是虚的,则只将调用对应于指针类型的析构函数
#include <iostream>
using namespace std;
class People{
public:
~People(){
cout<<"People Object Delete."<<endl;
}
};
class Student : public People{
~Student(){
cout<<"Student Object Delete."<<endl;
};
};
int main()
{
People *p = new Student;
delete p;
return 0;
}
输出结果:
People Object Delete.
Process returned 0 (0x0) execution time : 0.012 s
Press any key to continue.
二,如果析构函数是虚的,将调用实际指向的对象的析构函数
如果指针指向的是派生类的对象,将调用派生类对象的析构函数,然后再调用基类对象的析构函数。因此,使用虚析构函数可以确保正确的析构函数调用顺序。
#include <iostream>
using namespace std;
class People{
public:
//把基类的析构函数声明为虚的
virtual ~People(){
cout<<"People Object Delete."<<endl;
}
};
class Student : public People{
~Student(){
cout<<"Student Object Delete."<<endl;
};
};
int main()
{
People *p = new Student;
delete p;
return 0;
}
输出结果:
Student Object Delete.
People Object Delete.
Process returned 0 (0x0) execution time : 0.020 s
Press any key to continue.
1815

被折叠的 条评论
为什么被折叠?



