static class 成员和开关
static class members and switches
我遇到了一个小问题,我得到一个错误:
"C2361: initialization of *identifier* is skipped by 'default' label"
我使用内部 class 成员来设置我的方法中使用的所选方法。
这些方法使用此内部成员 (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
}
}
非常感谢任何提示或解决方案
您发布的代码存在很多问题。但假设没有其他问题,以下代码将产生您遇到的情况:
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;
}
会产生错误:
error C2361: initialization of 'apples' is skipped by 'default' label
这是因为您正试图在 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)
我遇到了一个小问题,我得到一个错误:
"C2361: initialization of *identifier* is skipped by 'default' label"
我使用内部 class 成员来设置我的方法中使用的所选方法。
这些方法使用此内部成员 (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
}
}
非常感谢任何提示或解决方案
您发布的代码存在很多问题。但假设没有其他问题,以下代码将产生您遇到的情况:
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;
}
会产生错误:
error C2361: initialization of 'apples' is skipped by 'default' label
这是因为您正试图在 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)