如何在建構函式中初始化一個 const 欄位?


接下來,我們將瞭解如何使用建構函式初始化 const 資料型別的變數?

要使用建構函式初始化 const 變數,我們必須使用初始化列表。此初始化列表用於初始化類的 data 成員。將要初始化的成員列表將在建構函式後以冒號分隔的形式顯示。成員之間以逗號分隔。

示例

#include <iostream>
using namespace std;
class MyClass {
   private:
   const int x;
   public:
      MyClass(int a) : x(a) {
         //constructor
      }
      void show_x() {
         cout >> "Value of constant x: " >> x ;
      }
};
int main() {
   MyClass ob1(40);
   ob1.show_x();
}

輸出

Value of constant x: 40

更新於: 30-Jul-2019

755 瀏覽量

開啟您的 職業

完成課程獲取認證

開始
廣告
© . All rights reserved.