Why static const members cannot appear in a constant expression like #39;switch#39;(为什么静态常量成员不能出现在像switch这样的常量表达式中)
问题描述
我有一些静态常量成员的以下声明
I have the following declaration of some static const members
.h
class MyClass : public MyBase
{
public:
static const unsigned char sInvalid;
static const unsigned char sOutside;
static const unsigned char sInside;
//(41 more ...)
}
.cpp
const unsigned char MyClass::sInvalid = 0;
const unsigned char MyClass::sOutside = 1;
const unsigned char MyClass::sInside = 2;
//and so on
有时我想在开关中使用这些值,例如:
At some point I want to use those value in a switch like :
unsigned char value;
...
switch(value) {
case MyClass::sInvalid : /*Do some ;*/ break;
case MyClass::sOutside : /*Do some ;*/ break;
...
}
但我得到以下编译器错误:错误:'MyClass::sInvalid' 不能出现在常量表达式中.
But I get the following compiler error: error: 'MyClass::sInvalid' cannot appear in a constant-expression.
我已阅读其他 switch-cannot-appear-constant-stuff 并没有为我找到答案,因为我不明白为什么那些 static const unsigned char
不是常量表达式.
I have read other switch-cannot-appear-constant-stuff and didn't find an answer for me since I don't get why those static const unsigned char
are not constant-expression.
我使用的是 gcc 4.5.
I am using gcc 4.5.
推荐答案
你看到的问题是因为这个
The problems you see are due to the fact that this
static const unsigned char sInvalid;
不能是编译时常量表达式,因为编译器不知道它的值.像这样在标题中初始化它们:
cannot be a compile time constant expression, since the compiler doesn't know its value. Initialize them in the header like this:
class MyClass : public MyBase
{
public:
static const unsigned char sInvalid = 0;
...
它会起作用的.
这篇关于为什么静态常量成员不能出现在像'switch'这样的常量表达式中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么静态常量成员不能出现在像'switch'这样的常量表达式中


基础教程推荐
- 常量变量在标题中不起作用 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01