如何使用结构来导航类成员函数中的switch语句?
我有一个结构,其中包含我想在switch语句中使用的数据(uint8_t,unit16_t,int16_t等)。当我尝试在需要读取此数据的另一个类中实现它时,我最初在临时文件中制作原型并不起作用。
以下是我的C ++代码的通用版本:
struct toSwitch{
const int one = 1;
const int two = 2;
};
struct toSwitch{
const int one = 1;
const int two = 2;
};
class testClass{
public:
void foo(){
switch (temp) {
case tosB.one:
cout << "ONE" << endl;
break;
case tosB.two:
cout << "TWO" << endl;
break;
default:
break;
}
}
private:
toSwitch tosB;
int temp = 1;
};
int main()
{
constexpr toSwitch tosA;
int swTest= 1;
switch (swTest) {
case tosA.one:
cout << "ONE" << endl;
break;
case tosA.two:
cout << "TWO" << endl;
break;
default:
break;
}
testClass b;
b.foo();
return 0;
}
在主例程中,struct可用于按预期移动switch语句。 (输出为“ONE”。)但是,当我在testClass中尝试相同的语句时,我收到编译错误。
在常量表达式中使用'this'
'this'不是常量表达式
我找到了一些有用的链接,但我还没有完全理解。为什么在主程序中使结构成为constexpr工作而不是在类中?
有没有办法初始化/强制数据结构为一个常量表达式,以便在switch语句中使用?
谢谢!
[1] switch case: error: case label does not reduce to an integer constant