下面是类成员变量初始化的一些情况,包括const 成员、static成员、static const 成员、引用类型成员、数组成员但是字符数组成员只能初始化为空,INT数组所有成员初始化为0,当然数组成员可以在构造函数体进行赋值。非静态const数据成员和引用成员只能在初始化列表初始化。 

  1. #include <iostream> 
  2. using namespace std; 
  3.  
  4. class CTestInitial 
  5.  private: 
  6.    const  int num1; 
  7.    static int num2; 
  8.    static const int num3; 
  9.    static const int bufLen = 128
  10.    char m_szBuf[bufLen]; 
  11.    int&  quoteNum; 
  12.  
  13.  public: 
  14.    CTestInitial(int& num) 
  15.    :m_szBuf() 
  16.    ,num1(0) 
  17.    ,quoteNum(num) 
  18.    {} 
  19.  
  20.  void Output() 
  21.  { 
  22.    cout<<quoteNum<<endl
  23.  } 
  24. }; 

 

下面测试引用类型成员的效果: 

  1. void  main() 
  2.    int num = 0
  3.    CTestInitial test(num); 
  4.    test.Output(); 
  5.  
  6.    num = 100
  7.    test.Output(); 

 

输出:

  1. 100 

另外test对象的m_szBuf数组的128个字符为 '\0'。