#include<iostream> #include<string> using namespace std; class Animal { public: Animal() { cout << "Animal 构造" << endl; } /*virtual ~Animal() { cout << "Animal 虚析构" << endl; }*/ virtual ~Animal() = 0;//纯虚析构也需要代码实现 virtual void speak() = 0; }; Animal::~Animal() { cout << "Animal 纯虚析构" << endl; } class Cat :public Animal { public: Cat(string name) { cout << "Cat 构造" << endl; m_Name = new string(name); } virtual void speak() { cout << *m_Name <<"小猫在说话" << endl; } ~Cat() { if (m_Name != NULL) { cout << "Cat 析构" << endl; delete m_Name; m_Name = NULL; } } string* m_Name; }; void test01() { Animal* animal = new Cat("Tom"); animal->speak(); delete animal; } int main() { test01(); //解决 父类指针在释放时无法调用子类的析构函数 的问题 system("pause"); return 0; }
#include <iostream> using namespace std; class Point {public: Point(){} virtual ~Point(){cout<<"executing Point destructor"<<endl;} }; class Circle:public Point {public: Circle(){} ~Circle(){cout<<"executing Circle destructor"<<endl;} }; int main() {Point *p=new Circle; delete p; return 0; }
原文链接: https://www.cnblogs.com/lyt888/p/12489073.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;
也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/335095
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!