本系列 C++ 相關文章 僅為筆者學習筆記記錄,用自己的理解記錄學習!C++ 學習系列將分為三個階段:基礎篇、STL 篇、高階數(shù)據(jù)結構與算法篇,相關重點內容如下:
- 基礎篇:類與對象(涉及C++的三大特性等);
- STL 篇:學習使用 C++ 提供的 STL 相關庫;
- 高階數(shù)據(jù)結構與算法篇: 手動實現(xiàn)自己的 STL 庫 及 設計實現(xiàn)高階數(shù)據(jù)結構,如 B樹、B+樹、紅黑樹等。
學習集:
- C++ 入門到入土?。?!學習合集
- Linux 從命令到網(wǎng)絡再到內核!學習合集
本期內容:C++ 類的基本成員函數(shù):析構函數(shù)的作用 及 自定義析構函數(shù)情形
目錄:
1. 析構函數(shù)的概念
2. 析構函數(shù)的特性
3. 代碼測試
4. 析構函數(shù)的使用情形
5. 析構順序問題 及 類類型成員與析構函數(shù)
6. 相關文章推薦
【 C++學習合集鏈接 】
1. 析構函數(shù)的概念
析構函數(shù):與構造函數(shù)功能相反,析構函數(shù)不是完成對對象本身的銷毀,局部對象銷毀工作是由編譯器完成的。而對象在銷毀時會自動調用析構函數(shù),完成對象中資源的清理工作。
注意:先銷毀,再調用析構函數(shù)!
2. 析構函數(shù)的特性
析構函數(shù)是特殊的成員函數(shù)!
特性:
- 析構函數(shù)名是在類名前加上字符 ~。
- 無參數(shù)、無返回值類型。
- 一個類只能有一個析構函數(shù)。若未顯式定義,系統(tǒng)會自動生成默認的析構函數(shù)。注意:析構函數(shù)不能重載!
- 對象生命周期結束時,C++編譯系統(tǒng)系統(tǒng)自動調用析構函數(shù)。
3 代碼測試
代碼如下:
#include<iostream>
using std::cout;
using std::endl;
class Date {
public:
/* 構造函數(shù) */
Date(int year = 1970, int month = 1, int day = 1) {
_year = year;
_month = month;
_day = day;
cout << "構造函數(shù)!" << endl;
}
/* 析構函數(shù) */
~Date() {
cout << "析構函數(shù)!" << endl;
}
void Print() {
cout << _year << "-" << _month << "-" << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
int main() {
{ /* d1 若出了 {} 生命周期就結束了! */
Date d1;
}
return 0;
}
4. 析構函數(shù)的使用情形
1. 如果沒有主動動態(tài)申請空間一般不必寫析構函數(shù)!
2. 若使用了 malloc 、new 等形式申請了空間需要手動寫析構函數(shù)(手動釋放空間)!
代碼示例
#include<iostream>
using std::cout;
using std::endl;
typedef int DataType;
/* 定義一個棧的及其構造函數(shù) */
class Stack {
public:
Stack(int capacity = 4) { // 結合參數(shù)缺省實現(xiàn):只要實例化必定是可用的棧(空間為:4)
_capacity = capacity;
_array = (DataType*)malloc(sizeof(DataType) * capacity); // 申請存儲空間
if (_array == nullptr) {
perror("malloc fail!\n");
return;
}
_size = 0;
}
/* 析構函數(shù):釋放在堆上申請的空間! */
~Stack(){
if(_array){
cout << "析構函數(shù)" << endl;
free(_array);
}
}
private:
DataType* _array; // 順序存儲方式
int _capacity; // 記錄當前棧的最大存儲量
int _size; // 記錄當前棧中的元素個數(shù)
};
int main() {
{
Stack stk;
}
return 0;
}
5. 析構順序問題 及 類類型成員與析構函數(shù)
點此跳轉文章來源:http://www.zghlxwxcb.cn/news/detail-469004.html
6. 相關文章推薦
1. C++ 學習 ::【基礎篇:12】:C++ 類的基本成員函數(shù):構造函數(shù)基本的定義與調用 |(無參構造與有參構造及缺省參數(shù)式構造)
2. C++ 學習 ::【基礎篇:13】:類的基本成員函數(shù):類類型成員與構造函數(shù)問題文章來源地址http://www.zghlxwxcb.cn/news/detail-469004.html
到了這里,關于C++ 學習 ::【基礎篇:14】:C++ 類的基本成員函數(shù):析構函數(shù)的作用 及 自定義析構函數(shù)情形的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!