1、靜態成員初始化(不能在構造函數或初始化列表中初始化)
1.1 所有靜態成員都可以在類定義之外初始化(通用),如下所示
class test { public: static int a; }; int test::a = 4; // 一般的靜態成員在類定義外初始化
1.2 特殊的靜態常量成員,可以在類內初始化,如下所示
class test { public: static const int a = 5; }; const int test::a; // 注意,此處成員定義非必需,可有可無,但是不能再次初始化
2、非靜態成員初始化
2.1 const成員變量只能在初始化列表中初始化
class test { public: test():a(5){} // const成員只能在初始化列表中初始化 private: const int a; };
2.2 非const成員變量在構造函數、初始化列表中初始化
class test { public: test():a(5){/* a = 5; */} // 非const成員在構造函數、初始化列表中初始化(嚴格說,構造函數中叫賦值,不是初始化) private: int a; };