• virtual析构函数的作用


    C++ Primter中讲“在 C++ 中,基类必须指出希望派生类重写哪些函数,定义为 virtual 的函数是基类期待派生类重新定义的,基类希望派生类继承的函数不能定义为虚函数”。

    析构函数是为了在对象不被使用之后释放它的资源,虚函数是为了实现多态。那么把析构函数声明为vitual有什么作用呢?,下面通过例子来说明一下vitual的用途。

    using namespace std;

    class Base
    {
    public:
      Base() {};     //Base的构造函数
      ~Base()        //Base的析构函数
      {
        cout << "the destructor of class Base!" << endl;
      };
      virtual void DoSomething() 
      {
        cout << "Do something in class Base!" << endl;
      };
    };
        
    class Derived : public Base
    {
    public:
      Derived() {};     //Derived的构造函数
      ~Derived()      //Derived的析构函数
      {
        cout << "the destructor of class Derived!" << endl;
      };
      void DoSomething()
      {
        cout << "Do something in class Derived!" << endl;
      };
    };
        
    int main()
    {
      Derived *pTest1 = new Derived();   //Derived类的指针
      pTest1->DoSomething();
      delete pTest1;
        
      cout << endl;
        
      Base *pTest2 = new Derived();      //Base类的指针
      pTest2->DoSomething();
      delete pTest2;
        
      return 0;
    }


    先看程序输出结果:
    1       Do something in class Derived!
    2       the destructor of class Derived!
    3       the destructor of class Base!
    4      
    5       Do something in class Derived!
    6       the destructor of class Base!

    从运行结果来看,pTest1运行比较正常,也好理解,pTest2运行了子类的Do something和父类的析构函数,并没有运行子类的析构函数,这样会造成内存泄漏。

    pTest2运行了子类的Do something量因为父类的Do something加了virtual。

    pTest2运行了父类的析构函数是因为父类的析构函数并没有加virtual,所以它并不会运行子类的析构函数。

    如果Base的析构函数加上virtual,那么pTest1和pTest2运行过程一样。

    总结:如果一个类有可能会被继承,那么它的析构函数最好加上virtual,不然出现内存泄漏问题找都找不到。

  • 相关阅读:
    c语言中编写标准身高体重对照表
    c语言实现约数的枚举
    c语言中循环输出1234567890
    c语言中为九九乘法增加横纵标题
    c语言中多重循环
    c语言中绘制金字塔
    c语言中双重循环
    c语言中绘制长方形
    当当网代码1
    当当网代码4
  • 原文地址:https://www.cnblogs.com/zhangnianyong/p/5588483.html
Copyright © 2020-2023  润新知