C++-析构函数

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

/*
析构函数
*/ 
#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; 
}

 

posted @ 2020-04-02 19:16  c语言我的最爱  阅读(237)  评论(0编辑  收藏  举报