#include <iostream>
using namespace std;
class A{
public:
A(){
p = new char[20];
strcpy(p, "obja");
cout << "this is A()--" << endl;
}
virtual ~A(){
delete []p;
cout << "this is ~A()---" << endl;
}
protected:
private:
char* p;
};
class B:public A{
public:
B(){
p = new char[20];
strcpy(p, "objb");
cout << "this is B()--" << endl;
}
~B(){
delete[]p;
cout << "this is ~B()---" << endl;
}
protected:
private:
char* p;
};
class C :public B{
public:
C(){
p = new char[20];
strcpy(p, "objc");
cout << "this is C()--" << endl;
}
~C(){
delete[]p;
cout << "this is ~C()---" << endl;
}
protected:
private:
char* p;
};
//不加virtual关键字 只调用父类A的析构,形成内存泄漏
// A()->B()->C()->~C()->~B()->~A()
void deleteobj(A* base){
delete base;
}
int main()
{
C *myc = new C();
deleteobj(myc);
system("pause");
return 0;
}
虚析构函数
最新推荐文章于 2022-12-15 13:14:42 发布