案例表达不是恒定的

时间:2011-11-08 11:42:23

标签: c++

我在switch语句中遇到'case expression not constant'错误。但是,标头提供了使用常量的定义,构造函数在其初始化列表中为它们提供了初始化。

此外,当我将鼠标悬停在“问题”语句上时,它会将它们标识为常量。

const int ThisClass::EXAMPLE_CONSTANT

error expression must have a constant value

这对我来说似乎有点违反直觉。我做了一些研究,发现了其他人的类似问题。他们被告知所有常量实际上必须在'main'中初始化,并且这是语言的限制。这是真的吗?这似乎不太可能。

5 个答案:

答案 0 :(得分:14)

case语句需要在编译时必须知道的整数值,这就是常量的含义。但在这个意义上,const成员实际上不是常量。它们只是只读的。

您可以使用enum

代替字段
class ThisClass
{
    public:

        enum Constants
        {
            EXAMPLE_CONSTANT = 10,
            ANOTHER_CONSTANT = 20
        };    
};

然后你可以写,

switch(c)
{
      case ThisClass::EXAMPLE_CONSTANT:
                   //code
                   break;
      case ThisClass::ANOTHER_CONSTANT:
                   //code
                   break;
};

答案 1 :(得分:4)

您需要一个“实际”编译时整数常量。 C ++中的const表示只读,而const变量可以 像int y = 0; const int x = y;一样进行初始化,使x成为初始化时y值的只读副本。

使用现代编译器,您可以使用enumconstexpr来存储(整数)编译时constness的成员:

class Foo {
public:
    static constexpr int x = 0;
    enum { y = 1 };
};

int main () {
    switch (0) {
    case Foo::x: ;
    case Foo::y: ;
    }
}

答案 2 :(得分:2)

这有点乱。在C ++中,const可以用于几个方面,比如声明实际常量,以及声明只读变量。

如果您声明:

const int x = 0;

在全局,名称空间或本地范围内,它是一个常量。您可以在需要常量表达式的地方使用它(例如大小写标签或数组大小)。但是,在类范围或函数参数中,它只是一个只读变量。

此外,如果您在类范围声明:

static const int x = 0;

这也是一个常数。

答案 3 :(得分:1)

案例标签中使用的常量必须是整数常量表达式整型常量表达式必须满足更严格的要求,而不仅仅是声明为const的整数对象。

非静态类成员不能在整数常量表达式中使用,因此您尝试执行的操作将无法编译。例如,如果静态类成员的初始化程序在使用点“可见”,则可以在整数常量表达式中使用。

答案 4 :(得分:0)

std::map + C ++ 11 lambdas变通办法

此方法允许非常量,应该给我们O(1)摊销What is the best way to use a HashMap in C++?

#include <ctime>
#include <functional>
#include <unordered_map>
#include <iostream>

int main() {
    int result;
    int key0 = std::time(NULL) % 3;
    int key1 = (key0 + 1) % 3;
    int key2 = (key0 + 2) % 3;
    std::unordered_map<int,std::function<void()>> m{
        {key0, [&](){ result = 0; }},
        {key1, [&](){ result = 1; }},
        {key2, [&](){ result = 2; }},
    };
    m[key0]();
    std::cout << key0 << " " << result << std::endl;
    m[key1]();
    std::cout << key1 << " " << result << std::endl;
    m[key2]();
    std::cout << key2 << " " << result << std::endl;
}

可能的输出:

1 0
2 1
0 2

要在课堂内使用,请不要忘记静态制作地图,如下所示:Why switch statement cannot be applied on strings?

相关问题