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'这样的常量表达式中
基础教程推荐
- c++ STL设置差异 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
