类的const数据成员既不能和static成员一样直接给出值或者在类体外初始化,也不能在构造函数中初始化。
初始化const数据成员的唯一机会是在构造函数的初始化列表中。
如下所示:
#include <iostream>
using namespace std;
class A{
public:
A():b(10){//只能在构造函数的初始化列表中对其进行初始化,其他地方均办不到
a = c =1;
}
int a;
const int b;
mutable int c;
void show1(){cout << a << b << c << endl;}
void show2()const{c++; cout << c << endl;}
void show3()const{cout << c << endl;}
};
int main(){
cout << "ok" << endl;
A a;
a.show2();
a.show3();
return 1;
}