• C++析构函数定义为虚函数(转载)


    转载:http://blog.csdn.net/alane1986/article/details/6902233

    析构函数执行时先调用派生类的析构函数,其次才调用基类的析构函数。如果析构函数不是虚函数,而程序执行时又要通过基类的指针去销毁派生类的动态对象,那么用delete销毁对象时,只调用了基类的析构函数,未调用派生类的析构函数。这样会造成销毁对象不完全。

     1 #include<iostream.h>
     2 #include<stdlib.h>
     3 
     4 class CPerson
     5 {
     6 public:
     7     virtual ~CPerson();       //基类的析构函数必须声明为虚函数,否则
     8 
     9                                 用delete销毁对象时会出错
    10 protected:
    11  char * m_lpszName;
    12  char * m_lpszSex;
    13 };
    14 
    15 class CStudent:public CPerson
    16 {
    17 public:
    18  ~CStudent();              //virtual可加也可不加
    19 protected:
    20  int m_iNumjber;           //学号
    21 };
    22 
    23 CPerson::~CPerson()
    24 {
    25  cout<<"~CPerson!"<<endl;
    26 }
    27 
    28 
    29 CStudent::~CStudent()
    30 {
    31  cout<<"~CStudent!"<<endl;
    32 }
    33 
    34 void main()
    35 {
    36  CPerson * poCPerson = new CStudent;        //构造一个CStudent的动态对象
    37  if(NULL==poCPerson)
    38  {
    39   exit(0);
    40  }
    41  delete poCPerson;
    42  cout<<"CStudent对象已经完成析构"<<endl;     //如果析构函数是非虚函数,
    43 
    44                                                那么CStudent对象就未析构完
    45  CStudent oCStudent;
    46 }

    输出:

    ~Student!

    ~CPerson!

    CStudent对象已经完成析构

    ~Student!

    ~CPerson!

    如果去掉~CPerson()前面的virtual,且将“CStudent对象已经完成析构”改为“CStudent对象未完成析构”。程序的执行结果为:

    ~CPerson!

    CStudent对象未完成析构

    ~Student!

    ~CPerson!

  • 相关阅读:
    laravel 表单接收
    Ubuntu查找通过apt命令已安装软件
    Centos7.2源码编译安装LA(N)MP
    文件和目录权限
    第六天 软件安装和管理
    第五天用户和组群账户管理
    第四天 文件和目录操作
    第三天 目录和文件
    第二天 linux命令
    oracle数据库学习第一天
  • 原文地址:https://www.cnblogs.com/chechen/p/6021953.html
Copyright © 2020-2023  润新知