C++構造函數和析構函數
類的構造函數:
類的構造函數是,每當我們創建該類的新對象時執行一類特殊的成員函數。
構造函數都會有完全相同的名字作為類,它冇有任何返回類型可言,甚至冇有作廢。構造可以為某些成員變量設置的初始值非常有用。
下麵的示例說明構造函數的概念:
#include <iostream> using namespace std; class Line { public: void setLength( double len ); double getLength( void ); Line(); // This is the constructor private: double length; }; // Member functions definitions including constructor Line::Line(void) { cout << "Object is being created" << endl; } void Line::setLength( double len ) { length = len; } double Line::getLength( void ) { return length; } // Main function for the program int main( ) { Line line; // set line length line.setLength(6.0); cout << "Length of line : " << line.getLength() <<endl; return 0; }
當上述代碼被編譯和執行時,它產生了以下結果:
Object is being created Length of line : 6
帶參數的構造函數:
默認的構造函數冇有任何參數,但如果需要,構造函數可以有參數。這有助於在其創建時的初始值賦給一個對象作為顯示,如下麵的例子:
#include <iostream> using namespace std; class Line { public: void setLength( double len ); double getLength( void ); Line(double len); // This is the constructor private: double length; }; // Member functions definitions including constructor Line::Line( double len) { cout << "Object is being created, length = " << len << endl; length = len; } void Line::setLength( double len ) { length = len; } double Line::getLength( void ) { return length; } // Main function for the program int main( ) { Line line(10.0); // get initially set length. cout << "Length of line : " << line.getLength() <<endl; // set line length again line.setLength(6.0); cout << "Length of line : " << line.getLength() <<endl; return 0; }
當上述代碼被編譯和執行時,它產生了以下結果:
Object is being created, length = 10 Length of line : 10 Length of line : 6
使用初始化列表來初始化字段:
使用初始化列表來初始化字段:
Line::Line( double len): length(len) { cout << "Object is being created, length = " << len << endl; }
上麵的語法等於如下語法:
Line::Line( double len) { cout << "Object is being created, length = " << len << endl; length = len; }
如果對於一個C類,則具有多個字段的X,Y,Z等,進行初始化,然後用可以使用相同的語法和由逗號分隔字段如下:
C::C( double a, double b, double c): X(a), Y(b), Z(c) { .... }
類析構函數:
析構函數是執行一個類的特殊成員函數時,它的類的對象超出範圍或當刪除表達式應用到一個指向類的對象。
析構函數將有完全相同的名稱作為前綴類帶有波浪號(〜),它可以冇有返回值,也不能采取任何參數。析構函數可以釋放資源,跳出程序很像在關閉文件之前,釋放內存等非常有用
以下舉例說明析構函數的概念:
#include <iostream> using namespace std; class Line { public: void setLength( double len ); double getLength( void ); Line(); // This is the constructor declaration ~Line(); // This is the destructor: declaration private: double length; }; // Member functions definitions including constructor Line::Line(void) { cout << "Object is being created" << endl; } Line::~Line(void) { cout << "Object is being deleted" << endl; } void Line::setLength( double len ) { length = len; } double Line::getLength( void ) { return length; } // Main function for the program int main( ) { Line line; // set line length line.setLength(6.0); cout << "Length of line : " << line.getLength() <<endl; return 0; }
讓我們編譯和運行上麵的程序,這將產生以下結果:
Object is being created Length of line : 6 Object is being deleted