关于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

 

转载于:https://www.cnblogs.com/withparadox2/p/6343280.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值