visual studio 2005中,字符串的问题

来源:百度知道 编辑:UC知道 时间:2024/07/03 04:41:26
控件关联的变量CString类型,要在MessageBox中显示出来,可是MessageBox中不能直接用字符串,怎么转换呢
char mc[60]="Data for Employee code: "+m_Ecode+" Employee name:"+m_Fname+" "+m_Lname+" is accepted.";
MessageBox(mc);

错误 1 error C2678: binary '+' : no operator found which takes a left-hand operand of type 'const char [25]' (or there is no acceptable conversion) e:\program\vc\myfirstapplication\myfirstapplication\myfirstapplicationview.cpp 154

错误 2 error C2664: 'CWnd::MessageBoxW' : cannot convert parameter 1 from 'char [60]' to 'LPCTSTR' e:\program\vc\myfirstapplication\myfirstapplication\myfirstapplicationview.cpp 155
string mc;
mc="Data for Employee code: "+m_Ecode+" Employee name:"+m_Fname+" "+m_Lname+" is accepted.";
MessageBox((LPCTSTR)mc);

错误 1 error C2065: 'string' : undeclared identifier

1、串通过操作符“+”连接以后不能赋值给char [60]类型的变量,但是可以赋值给string类型变量,如:
string mc = "A" + "BCD";
2、方法CWnd::MessageBoxW()接收的第一个参数类型不匹配,允许进行强制转换,比如:
MessageBox((LPCTSTR)mc);

针对问题补充:
1、如果使用类型string,那么需要
#include <string>
才能识别。
2、如果使用类型CString,那么等号右边的所有连接参数都必须为CString或char *类型的。m_Ecode应该不是这两种类型之一吧?其实可以将指令
mc="Data for Employee code: "+m_Ecode+" Employee name:"+m_Fname+" "+m_Lname+" is accepted.";
换成
mc.Format("Data for Employee code: %d Employee name: %s %s is accepted.", m_Ecode, m_Fname, m_Lname);
前提是m_Ecode为int类型,m_Fname和m_Lname为char *或CString类型。
3、同样,如果mc如下定义:
char mc[60];
也可以这样为之赋值:
sprintf(mc, "Data for Employee code: %d Employee name: %s %s is accepted.", m_Ecode, m_Fname, m_Lname);
效果与第2点相同。