静态类成员和开关

时间:2015-09-29 00:27:38

标签: c++ class int switch-statement const

我遇到了一个问题,我收到了一个错误:
"C2361: initialization of *identifier* is skipped by 'default' label"

我使用内部类成员来设置我的方法中使用的所选方法 这些方法使用此内部成员(static int)和一个开关来确定设置了哪种方法 编译时,开关需要一个初始值,所以我决定使用static const int。但是,VS仍然不高兴,我也无法改变static const int。 我很确定这个问题很重要,但是非常令人沮丧。

示例:

class test{
    public:
    static int Val;
    static void setVal(int val);
    static int doStuff(void);
};

test::setVal(int val){
    Val=val;
}

test::doStuff(){
    switch(Val){
    case 1:
    // do stuff
    case 2:
    // do other stuff
    default:
    // do default
    }
}

非常感谢任何提示或解决方案

1 个答案:

答案 0 :(得分:1)

There are numerous problems with he code you have posted. But assuming there are no other issues the following code will produce what you are experiencing:

test.h:

class test{
    public:
    static int Val;
    static void setVal(int val);
    static int doStuff(void);
};

test.cpp:

#include "test.h"

int test::Val = 0;

void
test::setVal(int val){
    Val=val;
}

int
test::doStuff(){
    switch(Val){
    case 1:
    // dostuff
        int apples = 1; /* problem line */
        break;
    default:
    // do default
        break;
    }
    return 0;
}

int main(int argc, char **argv)
{
    return 0;
}

Will produce the error:

error C2361: initialization of 'apples' is skipped by 'default' label

The reason for this is because you are trying to initialise a variable within the case statement. Visual Studio is complaining that there is no guarantee that the variable will be initialised because the case statement may be skipped over.

The question linked here gives the reason for this behavior.

But to put it briefly there is a chance that your code will jump to a case statement after the initialisation of your variable and visual studio does not allow such a case since it may lead to undefined behavior.

To quote the standard ( ISO C++ '03 - 6.7/3 ):

A program that jumps from a point where a local variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has POD type (3.9) and is declared without an initializer (8.5)