c++析构函数的调用

// ConsoleApplication2.cpp : 定义控制台应用程序的入口点。
//


#include "stdafx.h"
#include 

using namespace std;
class haitao{
private:
    int ageee;
public :
    int getAgee(){
        return ageee;
    }
    haitao(){
        cout << "无参构造函数被调用" << endl;
    }
    ~haitao(){
        cout << "析构函数被调用" << endl;
    }

};
void test(){
    haitao tt; //对象建立
    //方法结束时,由系统自动调用析构函数释放对象
}

int _tmain(int argc, _TCHAR* argv[])
{
    test();
    system("pause");
    return 0;
}


上面代码块执行结果:

c++析构函数的调用_第1张图片



接着,我们再看一个调用析构函数的例子:


#include "stdafx.h"
#include 

using namespace std;
class haitao{
private:
    int ageee;
public :
    int getAgee(){
        return ageee;
    }
    haitao(){
        cout << "无参构造函数被调用" << endl;
    }
    ~haitao(){
        cout << "析构函数被调用" << endl;
    }

};

void test(){
    haitao * pt; //动态的创建一个对象指针
    pt = new haitao();
    delete pt; // 必须使用delete释放指针所指向的内存空间,否则会内存泄漏
}
int _tmain(int argc, _TCHAR* argv[])
{
    test();
    system("pause");
    return 0;
}

上面代码块,打印结果如下:
c++析构函数的调用_第2张图片



值得注意的如下:
c++析构函数的调用_第3张图片

c++析构函数的调用_第4张图片

由此可以看见 ,由于没有使用delete关键字释放指针所指的内存单元,造成内存泄漏


QQ技术交流群:386476712

你可能感兴趣的:(C++基础,last,battle)