Destructor結束可能是:
- Automatic Class(定義時沒有額外加敘述者多為這個),該所屬Function(也可以是main)跑完,表示結束,會執行該Class的Destructor。
- Static Class,當整個程式跑完,才會結束、執行Destructor。
- Global Class,定義在任何一個Function外面,當所有函式的事情處理完之後,才被結束、執行Destructor。
Destructor定義方式與Constructor類似,為與Class名字相同的Function,但在最前方加"~"符號,不接受任何argument或是回傳值:
~Myclass();
MyClass.h
#include <string> using namespace std; class MyClass{ public: MyClass(int new_id, string new_message); ~MyClass(); private: int id; string message; };
MyClass.cpp
#include <iostream> #include <cstring> #include "MyClass.h" using namespace std; MyClass::MyClass(int new_id, string new_message){ id = new_id; message = new_message; cout << "Object no." << id << " constructor runs " << message << endl; } MyClass::~MyClass(){ cout << "Object no." << id << " destructor runs " << message << endl; }
Destructor.cpp
#include <iostream> #include <cstring> #include "MyClass.h" using namespace std; void create(); MyClass myclass_1( 1, "(global before main)" ); int main(){ cout << "\nMain Function: start------" << endl; MyClass myclass_2( 2, "(local automatic in main)" ); static MyClass myclass_3( 3, "(local static in main)" ); create(); cout << "\nMain Function: resumes----" << endl; MyClass myclass_4( 4, "(local automatic in main)" ); cout << "\nMain Function: ends-------" << endl; return 0; } void create(){ cout << "\nCreate Function: start----" << endl; MyClass myclass_5( 5, "(local automatic in create)" ); static MyClass MyClass_6( 6, "(local static in create)" ); MyClass myclass_7( 7, "(local automatic in create)" ); cout << "\nCreate Function: ends-----" << endl; }
Output:
Object no.1 constructor runs (global before main)Main Function: start------Object no.2 constructor runs (local automatic in main)Object no.3 constructor runs (local static in main)Create Function: start----Object no.5 constructor runs (local automatic in create)Object no.6 constructor runs (local static in create)Object no.7 constructor runs (local automatic in create)Create Function: ends-----Object no.7 destructor runs (local automatic in create)Object no.5 destructor runs (local automatic in create)Main Function: resumes----Object no.4 constructor runs (local automatic in main)Main Function: ends-------Object no.4 destructor runs (local automatic in main)Object no.2 destructor runs (local automatic in main)Object no.6 destructor runs (local static in create)Object no.3 destructor runs (local static in main)Object no.1 destructor runs (global before main)
No comments:
Post a Comment