為什么不能將開關語句應用于字符串?編譯以下代碼并得到type illegal.int main(){
// Compilation error - switch expression of type illegal
switch(std::string("raj"))
{
case"sda":
}}您不能在其中使用字符串。switch或case..為什么?是否有任何解決方案可以很好地支持類似于打開字符串的邏輯?
3 回答
森林海
TA貢獻2011條經驗 獲得超2個贊
switchstd::string
enum string_code {
eFred,
eBarney,
eWilma,
eBetty,
...};string_code hashit (std::string const& inString) {
if (inString == "Fred") return eFred;
if (inString == "Barney") return eBarney;
...}void foo() {
switch (hashit(stringValue)) {
case eFred:
...
case eBarney:
...
}}- 3 回答
- 0 關注
- 514 瀏覽
添加回答
舉報
0/150
提交
取消
