为什么析构函数常声明为虚函数
来源:互联网 发布:淘宝装修更换本地图片 编辑:程序博客网 时间:2024/05/01 00:14
昨天看了火狐的源码,看到里面很多,应该说几乎所有的析构函数都申明为虚函数,一时想不起来为啥,就上网查了一下,才知道这样做的作用是:
当你动态申请一个对象时,并且把这个对象的指针赋值给基类,这时当你用这个基类指针释放内存时,就有用了,因为这样可以用多态性原理调用对象实际的析构函数来析构内存。举例代码如下
#include "stdafx.h"#include <iostream>using namespace std;class CPen{public:CPen(int weight) : m_weight(weight){cout << "construct Cpen object.\n";}virtual ~CPen(){cout << "destruct CPen object\n";}//~CPen()//{//cout << "destruct CPen object\n";//}void PrintWeight() const{cout << "weight = " << m_weight;}private:int m_weight;};class CShape{public:int m_length;int m_thickness;int m_colour;};class CPencil : public CPen{public:CPencil(int weight, int length, int thickness, int colour) : CPen(weight){m_shapePtr = new CShape;m_shapePtr->m_length = length;m_shapePtr->m_thickness = thickness;m_shapePtr->m_colour = colour;//m_weight = weight; errorcout << "construct CPencil object.\n";}~CPencil(){cout << "destruct CPencil\n";delete m_shapePtr;}void ShowInfo() const{cout << "I am a pencil: ";PrintWeight();cout << " length = " << m_shapePtr->m_length << " thickness = " << m_shapePtr->m_thickness<< " colour = " << m_shapePtr->m_colour << endl;}private:CShape *m_shapePtr;};int _tmain(int argc, _TCHAR* argv[]){CPen *penPtr = new CPencil(10, 11, 12, 13);((CPencil *)penPtr)->ShowInfo();delete penPtr;penPtr = NULL;getchar();return 0;}
代码中注释了的析构函数是没有声明为虚函数的情况,大家如果也想测试的话,只要把注释去掉,在把虚析构函数注释起来,就可以对比出他们两的差别了。
- 为什么析构函数常声明为虚函数
- 为什么析构函数常声明为虚函数
- 为什么析构函数常声明为虚函数
- 为什么析构函数常声明为虚函数?
- 为什么构造函数不能声明为虚函数,析构函数可以声明为虚函数
- 为什么析构函数常常声明为虚函数
- c++ 为什么析构函数必须声明为虚函数
- 为什么要将基类的析构函数声明为虚函数
- 为什么构造函数不可以声明为虚函数,而析构函数最好声明为虚函数
- 为什么构造函数不可以被声明为虚函数而析构函数有时候必须声明为虚函数
- 为什么构造函数不能声明为虚函数,析构函数可以
- 为什么构造函数不能声明为虚函数,析构函数可以
- 为什么构造函数不能声明为虚函数,析构函数可以
- 为什么构造函数不能声明为虚函数,析构函数可以
- 为什么构造函数不能声明为虚函数,析构函数可以
- 为什么构造函数不能声明为虚函数,析构函数可以
- 为什么构造函数不能声明为虚函数,析构函数可以
- 为什么构造函数不能声明为虚函数,析构函数可以
- NET 4.0 - C# 4.0 新特性之并行运算(Parallel)
- Android Stagefright NuPlayer for HTTP live streaming
- GUI设计禁忌笔记
- 浅谈Action中获取session的信息(IoC模式)
- The Biggest Changes in C++11 (and Why You Should Care)
- 为什么析构函数常声明为虚函数
- 【观点】如何打造网站高性能的核心优势
- X86(IA32)段权限标志位CPL DPL RPL详解
- 一个很好的数据结构排序系统
- 菜谱
- hdu 3434 Sequence Adjustment
- TCPIP详解 习题一
- BWT轮换矩阵之完全桶排序算法
- The JSON Validator