除了上一節講到的類對象在創建時自動調用的構造函數,在對象銷毀時也會自動調用一個函數,它也和類名同名,也沒有返回值,名字前有一個個波浪線~,用來區分構造函數,它的作用主要是用做對象釋放后的清理善后工作。它,就是析構函數
成人app與構造函數相同的是,與類名相同,沒有返回值,如果用戶不定義,系統也會自動生成一個空的析構函數。而一旦用戶定義,則對象在銷毀時自動調用。
與構造函數不同的是,雖然他倆都為公開類型。構造可以重載,有多個兄弟,而析構卻不能重載,但它可以是虛函數,一個類只能有一個析構函數。
下面,我們以Student類為例,繼續添加析構函數,同時在構造函數和析構函數中都添加了輸出當前類的信息,用來辨別哪一個類的創建和銷毀,請大家仔細閱讀代碼:
#include<iostream> #include<Cstring> using namespace std; class Student { private: int num;//學號 char name[100];//名字 int score;//成績 public: Student(int n,char *str,int s); ~Student(); int print(); int Set(int n,char *str,int s); }; Student::Student(int n,char *str,int s) { num = n; strcpy(name,str); score = s; cout<<num<<" "<<name<<" "<<score<<" "; cout<<"Constructor"<<endl; } Student::~Student() { cout<<num<<" "<<name<<" "<<score<<" "; cout<<"destructor"<<endl; } int Student::print() { cout<<num<<" "<<name<<" "<<score<<endl; return 0; } int Student::Set(int n,char *str,int s) { num = n; strcpy(name,str); score = s; } int main() { Student A(100,"dot",11); Student B(101,"cpp",12); return 0; }
成人app請大家仔細理解上述代碼中的構造函數和析構函數,并注意主函數中定義了兩個對象A和B,并親自上機測試,可以看到運行效果如下:
可以看到對象A和B的構造函數的調用順序以及構造函數的調用順序,完全相反!原因在于A和B對象同屬局部對象,也在棧區存儲,也遵循“先進后出”的順序!
請大家務必親自上機測試!驗證結果!
本文固定URL:http://hnsaiyang.com/course/67