Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

c++ - Case expression not constant

I am getting a 'case expression not constant' error in a switch statement. However, the header provides a definition for the used constants, and the constructor provides initialisation for them in its initialization list.

Additionally, when I mouse over the "problem" statements it identifies them as constants.

const int ThisClass::EXAMPLE_CONSTANT

error expression must have a constant value

This seems a little counter-intuitive to me. I did some research and found a similar problem that someone else had. They were told that all constants must in fact be initialised in 'main' and that this was a limitation of the language. Is this really the case? It seems unlikely.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The case statements require integral value which must be known at compile-time, which is what is meant by constant here. But the const members of a class are not really constant in that sense. They're are simply read-only.

Instead of fields, you can use enum :

class ThisClass
{
    public:

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

And then you can write,

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...