C++ 析构函数
#include <iostream>
#include <cstdlib>using namespace std;char* strcpy(char *p, const char *s){char *t = p;while (*p++ = *s++){}return t;
}class Test{private:int m_x;int m_y;char* p; public://無參數的構造函數Test(){m_x = 0;m_y = 0;p = (char*)malloc(100);strcpy(p, "vvcat");}//析構函數 : ~+類型 沒有任何的參數~Test(){cout << "Test 的析構函數~Test() 被調用了" << endl;if (p != NULL) {cout << "p的堆空間被釋放了" << endl;free(p);p = NULL;}}void printT(){cout << "x : " << m_x << ", y: " << m_y << endl;}void init(int x, int y){m_x = x;m_y = y;}
};void test1(){Test t1; //調用無參數的構造函數//t1 是一個局部變量, 生命周期是test1()一樣的, 在test1()函數執行完畢需要 先銷毀t1變量//t1對象銷毀之前,系統就會默認的調用t1的析構函數t1.printT();return;
}int main(void){test1();
}
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀
總結
- 上一篇: C++ 判断点是否在圆的内部
- 下一篇: C++ 拷贝构造函数应用场景