C++ 程式設計中的建構函式


在本教程中,我們將討論一個瞭解 C++ 中的建構函式的程式。

建構函式是類的成員函式,用於初始化物件例項的建立。它們與父類同名,沒有返回值型別。

預設建構函式

示例

 動態演示

#include <iostream>
using namespace std;
class construct {
   public:
   int a, b;
   //default constructor
   construct(){
      a = 10;
      b = 20;
   }
};
int main(){
   construct c;
   cout << "a: " << c.a << endl
   << "b: " << c.b;
   return 1;
}

輸出

a: 10
b: 20

帶引數的建構函式

示例

 動態演示

#include <iostream>
using namespace std;
class Point {
   private:
   int x, y;
   public:
   Point(int x1, int y1){
      x = x1;
      y = y1;
   }
   int getX(){
      return x;
   }
   int getY(){
      return y;
   }
};
int main(){
   Point p1(10, 15);
   cout << "p1.x = " << p1.getX() << ", p1.y = " <<
   p1.getY();
   return 0;
}

輸出

p1.x = 10, p1.y = 15

更新於: 2020 年 3 月 12 日

522 次瀏覽

啟動你的 職業

完成課程獲得認證

開始
廣告