对象的销毁

如何进行销毁:在类的public中定义一个free函数,调用free函数进行销毁。

      class Test

         {

          int *p;

      public:

          Test() {  p = new int; }

          void free() { delect p; };

      }

    

析构函数:

    定义:~ClassName()

    作用:清理类申请的内存。

    注意:析构函数没有参数和返回值声明(不能重载),西沟函数在对象销毁时自动被调用。

#include <stdio.h>

class Test
{
    int mi;
public:
    Test(int i)
    {
        mi = i;
        printf("Test(): %d
", mi);
    }
    ~Test()
    {
        printf("~Test(): %d
", mi);
    }
};

int main()
{
    Test t(1);
    
    Test* pt = new Test(2);     // 1
                                // 2
    delete pt;                  // 2
                                // 1
    return 0;
}

    

析构函数定义准者:当类中定义了构造函数(申请了内存,打开了文件)。

原文地址:https://www.cnblogs.com/zsy12138/p/10713270.html