下面是类成员变量初始化的一些情况,包括const 成员、static成员、static const 成员、引用类型成员、数组成员。但是字符数组成员只能初始化为空,INT数组所有成员初始化为0,当然数组成员可以在构造函数体进行赋值。非静态const数据成员和引用成员只能在初始化列表初始化。
- #include <iostream>
- using namespace std;
- class CTestInitial
- {
- private:
- const int num1;
- static int num2;
- static const int num3;
- static const int bufLen = 128;
- char m_szBuf[bufLen];
- int& quoteNum;
- public:
- CTestInitial(int& num)
- :m_szBuf()
- ,num1(0)
- ,quoteNum(num)
- {}
- void Output()
- {
- cout<<quoteNum<<endl;
- }
- };
下面测试引用类型成员的效果:
- void main()
- {
- int num = 0;
- CTestInitial test(num);
- test.Output();
- num = 100;
- test.Output();
- }
输出:
- 0
- 100
另外test对象的m_szBuf数组的128个字符为 '\0'。