错误 C2664:MessageBoxW 无法将参数 2 从 'const char ' 转换为 'LPCWSTR'

Error C2664: MessageBoxW cannot convert argument 2 from 'const char ' to 'LPCWSTR'

我不断收到此错误消息:

State Error C2664 -- int MessageBoxW(HWND,LPCWSTR,LPCWSTR,UINT)': cannot convert argument 2 from 'const char *' to 'LPCWSTR' " 31

下面是我的代码。我知道这与在错误 class 中通过 what() 函数传递常量类型有关。由于某种原因,它是不兼容的。有什么想法吗?

// on startup execute to determine exceptions
try
{
    // instantiate object app of class AppWindow
    AppWindow app;

    // if(initialize function in class app is executed, and while the app is running, broadcast app)
    if (app.init())
    {
        while (app.isRun())
        {
            app.broadcast();
        }
    }
}

// if the following error is found, execute MessageBox function with following parameters
catch (const std::runtime_error& error)
{
    // parameters(has no owner window so displays independently)
    MessageBox(nullptr,  error.what(), L"An error has occured", MB_OK);
}

return 0;

std::runtime_error::what() returns const char*,所以你应该使用MessageBoxA(),而不是MessageBox(),也不是MessageBoxW()

MessageBoxA(nullptr,  error.what(), "An error has occured", MB_OK);

另外不要忘记从字符串文字中删除 L 前缀。

您可以使用 MessageBoxA() 并从字幕字符串中删除 L 前缀。或者将 e.what() 转换为 wchar_t 字符串。