如何在 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

更新于:2019 年 7 月 30 日

16K+ 次阅读

开启你的 职业生涯

完成课程,获取认证

开始学习
广告
© . All rights reserved.