码迷,mamicode.com
首页 > 编程语言 > 详细

C++-析构函数

时间:2020-04-02 19:53:57      阅读:75      评论:0      收藏:0      [点我收藏+]

标签:vat   test   names   构造函数   include   integer   ace   return   去除   

使用析构函数,进行函数的删除

/*
析构函数
*/ 
#include <iostream>

using namespace std; 


class Integer {
public:
    Integer(int i) {
        m_pi = new int; 
        *m_pi = i; 
    }
    ~Integer(void) {
        cout << "析构函数" << endl; 
        delete m_pi; 
    }
    void print(void) const{
        cout << *m_pi << endl; 
    }
private:
    int *m_pi; 
};

int main() {
    if(1) {
        Integer i(200); 
        i.print(); 
        cout << "test1" << endl; //没有使用,使用析构函数去除  
        Integer *p_i = new Integer(200); 
        p_i->print(); 
        delete p_i; 
        cout << "test2" << endl; 
    }
    cout << "test3" << endl; 
}

析构函数的执行顺序演示

/*
析构函数顺序演示 
*/ 
#include <iostream>

using namespace std; 

class A{
public:
    A(void) {
        cout << "A的构造函数" << endl; 
    }
    ~A(void) {
        cout << "A的析构函数" << endl; 
    }
}; 

class B{
public:
    B(void) {
        cout << "B的构造函数" << endl; 
    }
    ~B(void) {
        cout << "B的析构函数" << endl; 
    }
    A a; 
}; 


int main() {
    B b; 
    return 0; 
}

 

C++-析构函数

标签:vat   test   names   构造函数   include   integer   ace   return   去除   

原文地址:https://www.cnblogs.com/hyq-lst/p/12622423.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!