如何在 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP