Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/148.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 无法将参数1从';const wchar_t*';至';LPCTSTR';在MFC/C+中+;项目_C++_String_Mfc_Tchar_Lpcwstr - Fatal编程技术网

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

C++ 无法将参数1从';const wchar_t*';至';LPCTSTR';在MFC/C+中+;项目,c++,string,mfc,tchar,lpcwstr,C++,String,Mfc,Tchar,Lpcwstr,我在以下行中得到一个编译错误: 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

我在以下行中得到一个编译错误:

 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
我不知道如何解决此错误,我尝试了以下操作:

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创建一个新CString;它将根据需要自动转换为宽字符串和MBCS字符串

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

如果要在过时的MBCS模式下编译,可能需要使用,如CW2T,例如:

MessageBox(
    CW2T(e.getAllExceptionStr().c_str()),
    _T("Error initializing the sound player")
);
似乎您的
getAllExceptionStr()
方法返回一个
std::wstring
,因此对其调用
.c_str()
将返回一个
常量wchar\u t*

CW2T
wchar\u t
-string转换为
TCHAR
-string,在您的情况下(考虑MBCS编译模式),该字符串相当于
char
-string


但是请注意,从Unicode(
wchar\t
-strings)到MBCS(
char
-strings)的转换可能会有损。

LPCSTR=const char*
。您正在向它传递一个
常量wchar*
,这显然不是一回事


始终检查您是否向API函数传递了正确的参数
\T(“”
类型C-string是宽字符串,不能与该版本的
MessageBox()

一起使用,因为
e.getAllExceptionStr().C\U str()
返回宽字符串,则以下操作将起作用:

MessageBoxW(e.getAllExceptionStr().c_str(),L“初始化声音播放器时出错”)


注意
MessageBoxW
末尾的
W

我不知道如果你坚持使用ANSI,为什么
getAllExceptionStr
会返回一个宽字符串,但是你必须转换(注意:不是强制转换)它。我认为如果转换的目的只是将字符串作为临时传递给某个函数/方法,比如上面的
MessageBox()
,使用
CW2T
进行转换比创建新的
CString
实例更有效
CString
CW2T
有更多的功能,但也有更多的开销。此外,
CW2T
和其他ATL转换帮助程序还实现了对“小”字符串的优化,为小字符串分配堆栈缓冲区,而不是从堆中分配内存。@Mr.C64我相信您是对的,但我认为,担心调用MessageBox的开销可能是过早优化的典型表现。每个人都可以自由编写自己喜欢的代码。当有字符串作为参数转换为函数/方法(包括MessageBox)时,我更喜欢使用上述帮助程序:对我来说,这比在该上下文中使用CString的代码质量更高。每个人都有自己的编程风格。我认为如果调用foo()、bar()或MessageBox(),最好独立使用高质量的样式。