Cannot convert from 'const wchar_t *' to '_TCHAR *'

感情迁移 提交于 2019-12-30 18:44:06

问题


_TCHAR* strGroupName = NULL;
const _TCHAR* strTempName = NULL;

//Assign some value to strTempName

strGroupName = _tcschr(strTempName, 92) //C2440

I get an error at the above line while compiling this code in VS2008. In VC6 it compiles fine.

Error C2440: '=' : cannot convert from 'const wchar_t *' to '_TCHAR *'

What seems to be the problem and how do I fix it?


回答1:


Try casting it as

strGroupName = (_TCHAR*)_tcschr(strTempName, 92);

Seems to me that VS2008 got a little more strict on type casts, and won't automatically do them in some cases.




回答2:


strGroupName = const_cast<_TCHAR*>( _tcschr(strTempName, 92));

This is because the variant of the function you're using has a const _TCHAR* as input and returns a const _TCHAR*.

Another variant would be to have strTempName declared as _TCHAR*, and not as const _TCHAR*. In this case, the variant function having a _TCHAR* parameter and returning a _TCHAR* value is used.




回答3:


strGroupName should also be a pointer to const.

const _TCHAR* strGroupName = _tcschr(strTempName, 92);

No need to declare it until the call to initialise it.




回答4:


_tcschr is returning a const pointer. Hence the return value should be const _TCHAR* strGroupName = NULL; If it is not possible to change strGroupName to a const pointer then declare both the pointers as non-const pointers.



来源:https://stackoverflow.com/questions/999727/cannot-convert-from-const-wchar-t-to-tchar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!