如何在 C++ 類中初始化 const 成員變數?
接下來我們將瞭解如何使用建構函式初始化 const 型別成員變數?
如需使用建構函式初始化 const 值,我們必須使用初始化列表。此初始化列表用於初始化類的成員資料。要初始化的成員列表將在建構函式後冒號後顯示。成員間使用逗號分隔。
示例
#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
廣告