【问题标题】:CString to TCHARCString 到 TCHAR
【发布时间】:2012-08-09 08:16:40
【问题描述】:

经过很长时间的今天,我看到了这种转换:

void SomeFunction( LPCTSTR szText ) ...


CString str;
str.Format( "A Simple Sentence" );
SomeFunction( LPCTSTR( str ) );

编译正常。有关此转换的任何解释?

似乎大部分都可以,因为我不需要使用GetBuffer 并稍后释放它,也不需要创建带有字符串长度的new LPTSTR

【问题讨论】:

    标签: c++ cstring tchar


    【解决方案1】:

    是的,这没关系,因为CString 有转换运算符到LPCTSTRreference to operator

    msdn

    C++ 编译器自动应用定义的转换函数 用于将 CString 转换为 LPCTSTR 的 CString 类。

    因此,您不需要使用显式转换为LPCTSTR

    【讨论】:

      【解决方案2】:

      是的,这没关系。根据documentation,您只需要确保在返回指针期间不要修改字符串,您的代码运行良好。

      这基本上是CString 等效于std::string::c_str()

      虽然您通常不需要像代码那样显式使用强制转换。我认为您需要这样做的唯一原因是,如果您要转换为另一种类型,例如 SomeFunction 被定义为

      void SomeFunction(const std::basic_string<TCHAR>& str);
      

      在这种情况下,没有从 CStringstd::basic_string&lt;TCHAR&gt; 的隐式转换,因此您需要使用 LPCTSTR 作为中间值。

      【讨论】:

        猜你喜欢
        • 2011-11-02
        • 2015-08-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-04
        • 2010-10-08
        相关资源
        最近更新 更多