C++ 類構造函數 & 析構函數

C++ 類 & 對象 C++ 類 & 對象

類的構造函數

類的構造函數是類的一種特殊的成員函數,它會在每次創建類的新對象時執行。

構造函數的名稱與類的名稱是完全相同的,並且不會返回任何類型,也不會返回 void。構造函數可用於為某些成員變數設置初始值。

下麵的實例有助於更好地理解構造函數的概念:

實例

#include <iostream> using namespace std; class Line { public: void setLength( double len ); double getLength( void ); Line(); // 這是構造函數 private: double length; }; // 成員函數定義,包括構造函數 Line::Line(void) { cout << "Object is being created" << endl; } void Line::setLength( double len ) { length = len; } double Line::getLength( void ) { return length; } // 程式的主函數 int main( ) { Line line; // 設置長度 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); // 這是構造函數 private: double length; }; // 成員函數定義,包括構造函數 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; } // 程式的主函數 int main( ) { Line line(10.0); // 獲取默認設置的長度 cout << "Length of line : " << line.getLength() <<endl; // 再次設置長度 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) { length = len; cout << "Object is being created, length = " << len << endl; }

假設有一個類 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(); // 這是構造函數聲明 ~Line(); // 這是析構函數聲明 private: double length; }; // 成員函數定義,包括構造函數 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; } // 程式的主函數 int main( ) { Line line; // 設置長度 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

C++ 類 & 對象 C++ 類 & 對象