• 『转』VC++2008中的unsigned short和wchar_t


     转自:http://www.cnblogs.com/abiao/articles/1260221.html

    typedef  unsigned short XChar;

    typedef  unsigned short Wchar;


        TCHAR *pStr;//定义了UNICODE宏,这里等价wchar_t,下同
        XChar *pXCh;
        Wchar *pWch;
        pXCh = pWch; //ok

        pXChpStr = ; //illegal

        

        Xchar xch;

        TCHAR wCh;

        xch = wch; //ok


    error C2440: '=' : cannot convert from 'XChar *' to 'wchar_t *'

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

     

    今天在vc2008编译时遇到了如上的问题,百思不得其解。开始同事说是typedef的问题,可是pXCh = pWch;是正确的。

    查了很多资料,终于找到了答案。先转摘一篇文章。


    VC++2005中的unsigned short和wchar_t

     
    很多人可能会认为unsigned short和wchar_t是一个东西。其实不然。在C++标准中,wchar_t是个内建的类型,长度是16bit。所以很多编译器就直接 typedef unsigned short wchar_t。 但是事实上他们并不完全是一个东西。所以该写wchar_t还是写wchar_t。不要跟unsigned short混合起来写。
          举个例子。在VC++2005中有个编译开关叫: trait wchar_t as build-in type。如果打开这个选项那么wchar_t和unsigned short就完全是两个类型,也就是说 void function(wchar_t arg) 和void function(unsigned short)是两个参数不同的函数,反之则是一个函数。 这个在同一个工程中问题不大。但是如果你在两个不同的工程里
     trait wchar_t as build-in type这个选项设置不同的话,就会出现问题。具体原因大家自己去想。呵呵。懒得写了。

         总之,遵守标准来写代码。总是对的。

    ]

    哈哈,看了上面的内容终于有答案了。原来c++内置wchar_t。

    这就好比下面的代码:

        short sh;
        unsigned short ush;
        ush = sh; //ok
        short* pShort;
        unsigned short* pChar;
        pShort = pChar;// illegal

        long l;
        unsigned long ul;
        ul = l; //ok
        long *pL;
        unsigned long *pul;
        pL = pul;// illegal


    short可以隐式转换为unsigned short, 而short*不可以隐式转换为unsigned short*;

    long可以隐式转换为unsigned long, 而long*不可以隐式转换为unsigned long*;

    同理:TCHAR(wchar_t)可以隐式转换为XChar(unsigned short), 而TCHAR*(wchar_t*)不可以隐式转换为XChar*(unsigned short*)。

    解决方案:

    1,设置Property --> C/C++ --> language --> Treat wchar_t as Build-in Type为NO. wchar_t不是内置的了,而是typedef unsigned short wchar_t。

    2,用reinterpret_cast

    3,改typedef  unsigned short XChar 为 typedef wchar_t XChar。

  • 相关阅读:
    下拉选择框,允许手动输入和过滤
    MVC数据绑定
    一个页面多个ng-app注意事项
    modal 多层弹窗 Maximum call stack size exceeded 解决方法
    VS10x CodeMap 注册码(key):
    VS2015卸载再安装
    VS2015无法创建工程
    解决VS2015版本key required问题手动方案
    猪猪公寓—事后诸葛亮
    猪猪公寓——测试总结
  • 原文地址:https://www.cnblogs.com/abinxm/p/1782260.html
Copyright © 2020-2023  润新知