c++ - 静态类成员和开关

标签 c++ class int switch-statement constants

我遇到了一个小问题,我得到一个错误:
“C2361:*identifier* 的初始化被‘默认’标签跳过”

我使用一个内部类成员来设置我的方法中使用的所选方法。
这些方法使用此内部成员 (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
    }
}

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

最佳答案

您发布的代码存在许多问题。但假设没有其他问题,以下代码将产生您所遇到的情况:

测试.h:

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

测试.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;
}

会产生错误:

error C2361:“apples”的初始化被“default”标签跳过

这是因为您正试图在 case 语句中初始化一个变量。 Visual Studio 提示不能保证变量会被初始化,因为 case 语句可能会被跳过。

问题linked here给出了这种行为的原因。

但简而言之,您的代码有可能在变量初始化后跳转到 case 语句,而 visual studio 不允许这种情况,因为它可能导致未定义的行为。

引用标准(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)

关于c++ - 静态类成员和开关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32833810/

相关文章:

c++ - OOP 和类组合错误

c++ - 如何获取在当前 RB 文件中运行的 Ruby 类的实例? (在 C++ 中嵌入 Ruby)

c# - 如何枚举直接在继承类上定义的接口(interface)列表?

mysql - #1264 超出范围值修复?

java - 读取文件中的 int 时出现错误 NoSuchElementException

c++ - dumpbin 导出输出中的@number 是什么

c++ - 使用 sizeof 获得两个的最大幂

Python:使用虚拟类传递变量名?

c++ - 类对象在 int main() 中是 'undefined'

java - Int无法解除引用错误