zoukankan      html  css  js  c++  java
  • c++之虚析构函数

    1。虚析构函数:

      构造函数不能是虚函数。建立一个派生类对象时,必须从类

          层次的根开始,沿着继承路径逐个调用基类的构造函数

      析构函数可以是虚的。虚析构函数用于指引 delete 运算符正

          确析构动态对象 

    2. 定义了基类虚析构函数,基类指针指向的

        派生类动态对象也可以正确地用delete析构

    3 设计类层次结构时,提供一个虚析构函数,

         能够使派生类对象在不同状态下正确调用

         析构函数

     1 #include <iostream>
     2 using namespace std;
     3 
     4 class A
     5 {
     6 public:
     7     //virtual ~A()    //定义析构函数为虚析构函数时,使用基类真正引用派生类对象后,正确的调用了派生类的析构函数,释放了所有资源
     8     ~A()
     9     {
    10         cout << "A::~A() is called!
    ";
    11     }
    12 };
    13 class B:public A
    14 {
    15 public: 
    16     ~B()
    17     {
    18         cout << "B:~B() is called!
    ";
    19     }
    20 };
    21 void main()
    22 {
    23     //用基类指针建立派生类的动态对象
    24     A *a = new B();
    25     //用派生类指针建立派生类的动态对象
    26     B *b = new B();
    27     cout << "delete first object:
    ";
    28     //析构有基类建立的派生类对象,没有调用派生的析构函数
    29     delete a;
    30     cout << "delete secod object:
    ";
    31     //析构有派生类建立的派生类对象,正确的调用了派生类的析构函数
    32     delete b;
    33 }
     1 #include <iostream>
     2 using namespace std;
     3 
     4 class A
     5 {
     6 public:
     7     //virtual ~A()    //定义析构函数为虚析构函数时,使用基类真正引用派生类对象后,正确的调用了派生类的析构函数,释放了所有资源
     8     ~A()
     9     {
    10         cout << "A::~A() is called!
    ";
    11     }
    12 };
    13 class B:public A
    14 {
    15 public: 
    16     ~B()
    17     {
    18         cout << "B:~B() is called!
    ";
    19     }
    20 };
    21 void main()
    22 {
    23     //用基类指针建立派生类的动态对象
    24     A *a = new B();
    25     //用派生类指针建立派生类的动态对象
    26     B *b = new B();
    27     cout << "delete first object:
    ";
    28     //析构有基类建立的派生类对象,没有调用派生的析构函数
    29     delete a;
    30     cout << "delete secod object:
    ";
    31     //析构有派生类建立的派生类对象,正确的调用了派生类的析构函数
    32     delete b;
    33 }
  • 相关阅读:
    $.ajax()、$.post()、$.get()
    Json数据格式
    iOS UIButton 调节文字和图片的位置
    block 中使用 weakSelf
    iOS 移除导航栏黑线
    Swift 设置导航栏透明
    Xcode 8 证书管理 Signing for "xxxx" requires a development team.
    iOS 中文登录 中文参数 转码
    ios apple pay 证书配置
    Missing iOS Distribution signing identity for ... Xcode can request one for you.
  • 原文地址:https://www.cnblogs.com/Smart-Du/p/4336232.html
Copyright © 2011-2022 走看看