关于extern const变量无法用在case中的问题
有三个文件:
Test.h
1 #ifndef TEST_TEST_H 2 #define TEST_TEST_H 3 4 namespace test { 5 extern const int a; 6 } 7 8 #endif //TEST_TEST_H
Test.cpp
1 #include "Test.h" 2 namespace test { 3 const int a = 1; 4 }
main.cpp
#include "Test.h" int main() { int s = test::a; switch (s) { case test::a: break; } return 0; }
运行就会出现错误:
main.cpp:6:20: error: the value of 'test::a' is not usable in a constant expression
case test::a:
这里的错误提示很直观,因为当编译器在遇到case时,它希望看到一个具体数值,但是在这个编译单元中只include了Test.h文件,编译器不晓得test::a具体是多少,当然就罢工了。
当然,去掉Test.cpp中的代码,并且将Test.h改为 const int a = 1; 这样可以通过编译,但const会导致internal linkage,使得可能在内存中有多份拷贝,这不是我想要的。
http://stackoverflow.com/questions/5579028/how-to-use-switch-with-extern-constants
可以使用enum来解决这个问题,enum中的变量本身是整数的一个别名,程序并不会对其分配内存空间(类似于#define?)。删掉Test.cpp,编辑Test.h为:
Test.h
1 #ifndef TEST_TEST_H 2 #define TEST_TEST_H 3 4 namespace test { 5 enum { 6 a = 1 7 }; 8 } 9 10 #endif //TEST_TEST_H