(转载)http://www.189works.com/article-45135-1.html
Const成员如其它任何成员一样,简单考虑其出现在三个位置:全局作用域、普通函数内部、类里面。
下面请看测试代码:
1 #include "stdafx.h" 2 #include 3 4 using namespace std; 5 6 class A 7 { 8 public: 9 const int j; 10 //const int k = 3; 11 const static int i; 12 }; 13 14 //const static int A::i = 0; 15 const int A::i = 1; 16 17 //const int j; 18 int _tmain(int argc, _TCHAR* argv[]) 19 { 20 //const int i; 21 cout << A::i << endl; 22 return 0; 23 }
得出以下结论:
1、const常量在全局作用域声明时必须初始化,否则无法通过编译。
2、const常量在普通函数中(此处为main函数)中一样,也必须在声明时就进行初始化。
3、在类(此处为A)定义体中,从const常量j可以看出,不用初始化也能通过声明。有特殊原因,从const常量 k可以看出,不能在类定义体中进行初始话(原因见5)。
4、同理const static也可以在类定义体中声明,而在类外部初始化(此处为const static int i)。但注意,此处的i可以在类定义体中进行初始化。
5、C++规定,只有“const static的整形成员”才可以在类定义体中进行初始化。