C++ 預設建構函式


類建構函式是類的特殊成員函式,它在建立該類的物件的時候執行。

建構函式的名稱與類的名稱完全相同,但它沒有任何返回型別,甚至連 void 都沒有。建構函式對於為某些成員變數設定初始值非常有用。

下面的例子說明了建構函式的概念 −

示例

 線上示例

#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

更新日期:2019 年 7 月 30 日

234 人檢視

開啟您的 職業

完成課程即可獲得認證

開始
廣告
© . All rights reserved.