C++在switch中使用int时非常奇怪的行为

use*_*955 0 c++ int case switch-statement

我使用以下switch语句得到一些非常奇怪的行为:

string recognise_mti(int mti_code)
{
switch(mti_code)
    {
    case 1100:
    case 1101:
        return (mti_code + " (Auth. Request/Repeat)"); break;

    default:
        return (mti_code + " (NOT RECOGNISED)"); break;
    }
}
Run Code Online (Sandbox Code Playgroud)

它似乎根据输入整数返回各种各样的东西.它可能会变成一个愚蠢的错误,但到目前为止,我无法识别它.感谢任何帮助.

Oli*_*rth 10

既不是mti_code也不" (Auth. Request/Repeat)"std::string.所以实际上,所有添加的内容都是指针添加.所以你最终会得到一个随机的(可能是无效的)指针,然后将其隐式转换为a std::string.

试试这个:

#include <sstream>

...

std::stringstream ss;
ss << mti_code;
switch(mti_code)
    {
    case 1100:
    case 1101:
        ss << " (Auth. Request/Repeat)"; break;

    default:
        ss << " (NOT RECOGNISED)"; break;
    }
return ss.str();
Run Code Online (Sandbox Code Playgroud)