无法在 MFC / C++ 项目中将参数 1 从'const wchar_t *'转换为'LPCTSTR'

Cannot convert parameter 1 from 'const wchar_t *' to 'LPCTSTR' in MFC / C++ project

本文关键字:wchar const LPCTSTR 转换 MFC C++ 项目 参数      更新时间:2023-10-16

我在以下行收到编译错误:

 MessageBox(e.getAllExceptionStr().c_str(), _T("Error initializing the sound player"));
Error   4   error C2664: 'CWnd::MessageBoxA' : cannot convert parameter 1 from 'const wchar_t *' to 'LPCTSTR'   c:usersdanieldocumentsvisual studio 2012projectsmytest1mytest1main1.cpp 141 1   MyTest1

我不知道如何解决此错误,我尝试了以下方法:

MessageBox((wchar_t *)(e.getAllExceptionStr().c_str()), _T("Error initializing the sound player"));
MessageBox(_T(e.getAllExceptionStr().c_str()), _T("Error initializing the sound player"));

我正在使用"使用多字节字符集"设置,但我不想更改它。

最简单的方法是简单地使用 MessageBoxW 而不是 MessageBox

MessageBoxW(e.getAllExceptionStr().c_str(), L"Error initializing the sound player");

第二种最简单的方法是从原始语言创建一个新的CString;它将根据需要自动转换为宽字符串和MBCS字符串。

CString msg = e.getAllExceptionStr().c_str();
MessageBox(msg, _T("Error initializing the sound player"));

LPCSTR = const char* .你传递它一个const wchar*,这显然不是一回事。

始终检查是否向 API 函数传递了正确的参数。 _T("") C 字符串类型是宽字符串,不能与该版本的 MessageBox() 一起使用。

由于e.getAllExceptionStr().c_str()返回宽字符串,因此以下内容将起作用:

MessageBoxW(e.getAllExceptionStr().c_str(), L"Error initializing the sound player");

请注意MessageBoxW末尾的W;

如果你想在过时的MBCS模式下编译,你可能想要使用ATL/MFC字符串转换助手,如CW2T,例如:

MessageBox(
    CW2T(e.getAllExceptionStr().c_str()),
    _T("Error initializing the sound player")
);

似乎您的getAllExceptionStr()方法返回了一个std::wstring,因此对其调用.c_str()会返回一个const wchar_t*

CW2Twchar_t -string 转换为 TCHAR -string,在您的情况下(考虑到 MBCS 编译模式),这等效于 char -string。

但请注意,从Unicode(wchar_t字符串)到MBCS(char字符串)的转换可能是有损的。