当类中用到一些固定值时,希望将其定义为const成员变量,防止被修改。
但因为const成员变量因为初始化之后就不能修改,因此只能在构造函数的初始化列表中初始化
如果是数组,则没有办法在初始化列表中初始化,必须定义为static,放在类外定义
例子:
//const_array.h #include <iostream> using namespace std; class Base{ public: Base() : _cia(1){cout << "Base constructor was called" << endl;} void get(); private: const int _cia; static const int _ciaa[10]; }; class Derive : public Base{ }; //const_array.cpp const int Base::_ciaa[10] = {0,1,2,3,4,5,6,7,8,9}; void Base::get() { cout << "the value of _cia is: " << _cia << endl; cout << "the value of _ciaa is: " << endl; for(int i = 0; i < 10 ; i++) cout << _ciaa[i] << endl; } //const_array_client.cpp #include <iostream> #include "const_array.h" using namespace std; int main(){ Derive d; d.get(); return 0; }
输出:
Base constructor was called the value of _cia is: 1 the value of _ciaa is: 0 1 2 3 4 5 6 7 8 9