[英]Cannot convert parameter 1 from 'const wchar_t *' to 'LPCTSTR' in MFC / C++ project
I get a compilation error on the line: 我在行上遇到编译错误:
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:\users\daniel\documents\visual studio 2012\projects\mytest1\mytest1\main1.cpp 141 1 MyTest1
I don't know how to resolve this error, I tried the following: 我不知道如何解决这个错误,我尝试了以下方法:
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"));
I am using the setting "Use Multi-Byte Character Set" and I don't want to change it. 我正在使用“使用多字节字符集”设置,我不想更改它。
The easiest way is simply to use MessageBoxW
instead of MessageBox
. 最简单的方法是使用MessageBoxW
而不是MessageBox
。
MessageBoxW(e.getAllExceptionStr().c_str(), L"Error initializing the sound player");
The second easiest way is to create a new CString from the original; 第二种最简单的方法是从原始创建一个新的CString; it will automatically convert to/from wide string and MBCS string as necessary. 它会根据需要自动转换为宽字符串和MBCS字符串。
CString msg = e.getAllExceptionStr().c_str();
MessageBox(msg, _T("Error initializing the sound player"));
LPCSTR = const char*
. LPCSTR = const char*
。 You are passing it a const wchar*
, which clearly is not the same thing. 你传给它一个const wchar*
,这显然不是一回事。
Always check that you are passing API functions the right parameters. 始终检查您是否正在向API函数传递正确的参数。 _T("")
type C-string are wide strings and can't be used with that version of MessageBox()
. _T("")
类型C字符串是宽字符串,不能与该版本的MessageBox()
。
As e.getAllExceptionStr().c_str()
is returning wide string then the following will work: 当e.getAllExceptionStr().c_str()
返回宽字符串时,以下内容将起作用:
MessageBoxW(e.getAllExceptionStr().c_str(), L"Error initializing the sound player");
Note the W
on the end of MessageBoxW
; 注意MessageBoxW
末尾的W
;
If you want to compile in the obsolete MBCS mode, you may want to use the ATL/MFC string conversion helpers , like CW2T
, eg: 如果要在过时的MBCS模式下编译,可能需要使用ATL / MFC字符串转换助手 ,如CW2T
,例如:
MessageBox(
CW2T(e.getAllExceptionStr().c_str()),
_T("Error initializing the sound player")
);
It seems that your getAllExceptionStr()
method returns a std::wstring
, so calling .c_str()
on it returns a const wchar_t*
. 似乎你的getAllExceptionStr()
方法返回一个std::wstring
,所以在它上面调用.c_str()
会返回一个const wchar_t*
。
CW2T
converts from wchar_t
-string to TCHAR
-string, which in your case (considering the MBCS compilation mode), is equivalent to char
-string. CW2T
从wchar_t
-string转换为TCHAR
-string,在您的情况下(考虑MBCS编译模式),相当于char
-string。
Note however that conversions from Unicode ( wchar_t
-strings) to MBCS ( char
-strings) can be lossy. 但请注意,从Unicode( wchar_t
-strings)到MBCS( char
-strings)的转换可能是有损的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.