C++中虚析构函数
来源:互联网 发布:c语言键盘钩子 编辑:程序博客网 时间:2024/06/08 09:40
我们通常用将基类的析构函数设置为虚函数。可是,为什么要这样做呢?下面用一个小例子来说明:
class Base{public: Base() {}; virtual ~Base() {cout<<"Output from the destructor of class Base!"<<endl; }; virtual void DoSomething() { cout << "Do something in class Base!" << endl; };};class Derived : public Base{public: Derived() {}; ~Derived() { cout << "Output from the destructor of class Derived!" << endl; }; void DoSomething() { cout << "Do something in class Derived!" << endl; };};int main(){ Base *pTest=new Derived; pTest->DoSomething(); delete pTest;}
Do something in class Derived!
Output from the destructor of class Derived!
Output from the destructor of class Base!
如果如果把类Base析构函数前的virtual去掉,输出的结果是:
Do something in class Derived!
Output from the destructor of class Base!
当然,并不是要把所有类的析构函数都写成虚函数。因为当类里面有虚函数的时候,编译器会给类添加一个虚函数表,里面来存放虚函数指针,这样就会增加类的存储空间。所以,只有当一个类被用来作为基类的时候,才把析构函数写成虚函数。
所以注意如果基类不是虚析构函数的话可能会有以下两点问题:
1、子类所分配的内存不能被释放
2、子类中成员变量类所分配的内存也不能被释放,因为子类析构函数没有被调用,其变量的析构函数肯定也没被调用了
0 0
- [C/C++]C函数
- c 函数
- C函数
- C 函数
- C函数
- 【C++】函数
- C 函数
- C++:函数
- C函数
- [C++]函数
- C函数
- c 函数
- C函数
- [C++]函数
- C函数
- 【c++】函数
- 【C++】函数
- C 函数
- 冒泡排序
- java SE复习笔记25
- java 在jtextarea(文本框)里显示拖动进来文件的路径
- SQL Sever中对表的操作
- 第三周
- C++中虚析构函数
- 网上看到的一道腾讯面试题
- mybatis返回对象包含Long类型主键值 oracle数据库
- 第一篇
- windows 下用 easybcd修复ubuntu15.04启动项
- 给JTextAear添加背景图片
- UILabel随文字的多少重置它的frame
- 测试用例要素
- 如何在阿里云主机中设置二级域名开通子网站