C++入門經典-例7.3-析構函數的調用
阿新 • • 發佈:2017-09-19
turn gif style title 變量 .com 應用 clu image
View Code
1:析構函數的名稱標識符就是在類名標識符前面加“~”。例如:
~CPerson();
2:實例代碼:
(1)title.h
#include <string>//title是一個類,此為構造了一個類 #include <iostream> using std::string; class title{ public: title(string str);//這是一個構造函數 title();//這是一個無參構造函數 ~title();//這就是一個析構函數,執行的是收尾工作。 string m_str;//成員變量 };
(2)title.cpp
#include "stdafx.h" #include <iostream> #include "title.h" using std::cout; using std::endl; title::title(string str) { m_str = str; cout<<str<<endl; } title::title()//此為空構造函數,當未定義構造函數時,編譯器就會自動調用此函數 { m_str = "無名標題"; cout<<"這只是一個無名標題標題...View Code"<<endl; } title::~title()//這是一個析構函數,當類的對象被銷毀時,編譯器就會調用類的析構函數。 { cout<<"標題"<<m_str<<"要被銷毀了"<<endl; }
(3)main.cpp
// 7.3.cpp : 定義控制臺應用程序的入口點。 // #include "stdafx.h" #include "title.h" #include <iostream> using std::cout; using std::endl; int main() {View Codestring str("Hello World!!!!"); title out(str); if (true) { title t; } cout << "if執行完成" << endl; return 0; }
運行結果:
C++入門經典-例7.3-析構函數的調用