[英]c++ type conversion: error C2440: 'initializing' : cannot convert from 'HRESULT' to 'std::basic_string<_Elem,_Traits,_Alloc>'
I tried this in Visual studios 2012: 我在Visual Studios 2012中尝试了以下方法:
TCHAR szPath[MAX_PATH];
std::wstring applicationdatafolder = SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, 0, szPath);
MessageBox(NULL, applicationdatafolder, NULL, MB_OK);
I got those errors: 我得到那些错误:
Error C2440: 'initializing' : cannot convert from 'HRESULT' to 'std::basic_string<_Elem,_Traits,_Alloc>' (2nd row) 错误C2440:“正在初始化”:无法从“ HRESULT”转换为“ std :: basic_string <_Elem,_Traits,_Alloc>”(第二行)
Error C2664: 'MessageBoxW' : cannot convert parameter 2 from 'std::wstring' to 'LPCWSTR' (3rd row) 错误C2664:“ MessageBoxW”:无法将参数2从“ std :: wstring”转换为“ LPCWSTR”(第3行)
the SHGetFolderPath
function do return a HRESULT
to show if everything went right. SHGetFolderPath
函数确实返回一个HRESULT
以显示一切是否正确。 The actual "string" will be stored where last parameter points to: ergo into szPath
. 实际的“字符串”将存储在最后一个参数指向的位置:ergo到szPath
。 Now what you want is to construct the string from this char array via std::wstring applicationdatafolder (szPath)
and use it 现在,您想要的是通过std::wstring applicationdatafolder (szPath)
从此char数组构造字符串并使用它
addendum for Qs emerged in comments Q的附录出现在评论中
wstring foo(bar)
vs wstring foo = bar
afaik (feel free to edit if im wrong) the usage of the copy constructor is more efficient: wstring foo(bar)
VS wstring foo = bar
据我所知(随意编辑,如果我错了)的拷贝构造函数的使用更有效:
wstring foo(bar)
bar
为bar
内容分配足够的内存 bar
从bar
复制内容 wstring foo = bar
is essentialy wstring foo(); foo = bar;
wstring foo = bar
是必需的wstring foo(); foo = bar;
wstring foo(); foo = bar;
wstring foo
calls the default constructor without params) 创建一个新的空 wstring( wstring foo
调用不带参数的默认构造函数) operator=
致电operator=
bar
分配足够的空间来存储bar
内容 bar
从bar
复制内容 of course the compiler will probably recognize the redundant steps and optimize the code, but by using the former version we write efficient code in first place and don't rely on compiler optimiziation 当然,编译器可能会识别冗余的步骤,优化代码,但通过使用以前版本中,我们写在第一位高效的代码,不依赖于编译器optimiziation
also the former version is somewhat clearer as it reads as "make a wstring
named foo
from bar
" and latter is "make a wstring
named foo
and assign bar
to it". 同样,前一个版本的含义更为清晰,因为其读为“从bar
创建一个名为foo
的wstring
”,而后者为“创建一个名为foo
的wstring
并为其分配bar
”。 Pay attention to the fakt bar
can be of some arbitrary type and though compiler understands what you want, it may seem look strange to have a string
and some mywierdtype
in an assignment. 注意fakt bar
可以是任意类型,尽管编译器了解您想要的内容,但在赋值中包含string
和某些mywierdtype
看起来似乎很奇怪。
TCHAR szPath[MAX_PATH];
SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, 0, szPath);
std::wstring applicationdatafolder(szPath);
MessageBox(NULL, applicationdatafolder.c_str(), NULL, MB_OK);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.