拈花小仙 发表于 2014-7-26 08:06:02

为什么会出错呢?

本帖最后由 拈花小仙 于 2014-7-26 11:34 编辑

#include <Windows.h>
#include <iostream>
int main()
{
    LPWSTR szString = TEXT("hello");
    TCHARlpString;
    MessageBox(NULL,szString,TEXT("LPSTR"),MB_OK);
    CopyMemory(lpString,szString,lstrlen(szString)+1);
    MessageBox(NULL,lpString,TEXT("CHAR"),MB_OK);

    return 0;
}
C++编程小组

メ㊣逆ご帅☆ 发表于 2014-7-26 08:06:03

没有发出错误提示。不知道我们编译出现的错误是否一致首先我项目属性设置的是使用ASCII字符集
LPWSTR szString = TEXT("hello");
error C2440: 'initializing' : cannot convert from 'char ' to 'unsigned short *'
      Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast


类型不一致
定义的是宽字符的变量。项目属性设置的是使用ASCII字符集,TEXT因此会把hello转换成ASCII的形式。于是无法赋值
修改成LPWSTR szString = L"hello";把hello转换成宽字符。或者把项目属性设置为使用UNICODE字符集,这里选择前者



MessageBox(NULL,szString,TEXT("LPSTR"),MB_OK);
error C2664: 'MessageBoxA' : cannot convert parameter 2 from 'unsigned short *' to 'const char *'
      Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast

同样的项目属性设置的是使用ASCII字符集,MessageBox=MessageBoxA,也就是使用ASCII字符串作为参数
这里却用了szString宽字符
索性干脆这样改MessageBoxW(NULL,szString,L"LPSTR",MB_OK);


CopyMemory(lpString,szString,lstrlen(szString)+1);
error C2664: 'lstrlenA' : cannot convert parameter 1 from 'unsigned short *' to 'const char *'
      Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast


lstrlen因为项目属性设置的是使用ASCII字符集,所以lstrlen=lstrlenA无法获取szString大小,那么
CopyMemory(lpString,szString,lstrlenW(szString)+1);


不过上面几乎是打补丁式的做法。干脆这样

#include <Windows.h>
#include <iostream>
int main()
{
    LPSTR szString = "hello";//直接改
    TCHARlpString;
    MessageBox(NULL,szString,TEXT("LPSTR"),MB_OK);
    CopyMemory(lpString,szString,lstrlen(szString)+1);
    MessageBox(NULL,lpString,TEXT("CHAR"),MB_OK);
       
    return 0;
}


浮砂 发表于 2014-7-26 11:04:25

力挺小仙儿!

CopyMemory(lpString,szString,lstrlen(szString)+1);//这句有问题。
//因为是Unicode码,所占字节比Ascii大一倍。所以(lstrlen(szString)+1)*2就好啦

羽随风 发表于 2014-7-26 11:32:12

学些了 看看

智商是硬伤 发表于 2015-8-23 10:17:06

{:7_146:}
页: [1]
查看完整版本: 为什么会出错呢?