Friday, April 25, 2008

C++ error C2664:解决方法(转)

error C2664: 'void ATL::CStringT::Format(const wchar_t *,...)' : cannot convert parameter 1 from 'const char [4]' to 'const wch



CString s;

s.Format("%2d", num1);

but it generates the following error message when compiling:

d:\my documents\visual studio 2005\projects\pt24\pt24\expression.cpp(74) : error C2664: 'void ATL::CStringT::Format(const wchar_t *,...)' : cannot convert parameter 1 from 'const char [4]' to 'const wchar_t *'

with

[

BaseType=wchar_t,

StringTraits=StrTraitMFC_DLL

]

Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast



Your project is UNICODE enabled so CString format expects an UNICODE string instead of an ASCII one. You need to use the _T macro to create an UNICODE string:

str.Format(_T("%2d"), 42);

You can also change you project settings to use ASCII if you wish. Go to Project properties, Configuration Properties, General and you'll find an option named "Character Set". Change it to "Use Multi-Byte Character Set".