【问题标题】:Cannot construct CString from a char无法从 char 构造 CString
【发布时间】:2019-10-31 09:26:14
【问题描述】:

在VS2008中,我尝试从一个char构造一个CString,如下:

CString str = CString(_T('A') + 5);

但是会得到如下编译错误:

错误 C2440: '' : 无法从 'int' 转换为 'CString'

我相信 TCHAR 和 int 在 C++ 中是可交换的,为什么它拒绝接受 TCHAR 类型参数来构造 CString?

该行的目的是构造一个只有一个字符_T('F') 的CString。不要拿“A5”。

我尝试了解编译器如何处理代码,如下:

  1. 它将首先将 _T('A') 提升为整数。

  2. 它将_T('A')的整数值加5。

  3. 它会得到一个新的整数,但找不到将它转换回TCHAR的方法,它可以用作CString构造函数的输入参数。

【问题讨论】:

  • 停止使用 tchar。在这里查看我的答案:stackoverflow.com/a/50572941/104458
  • 我不确定你想做什么,但如果你想得到A5,那么str.Format(L"%c%d", 'A', 5); 就可以了。
  • @MaxVollmer,CString 有一个可以从 TCHAR 构造的构造函数
  • @Blaze,我正在尝试用一个字符 _T('F') 构造一个 CString。
  • 那么你可能想要CStringA((char)('A' + 5))CStringW((wchar_t)(L'A' + 5))

标签: c++ char c-strings


【解决方案1】:

接受charwchar_tCstringT 构造函数是explicit。请参阅docs

C++ 中的explicit 说明符意味着不允许编译器对参数进行隐式转换。另见explicit specifier

因此编译器不能(不允许)将int 值隐式转换为charwchar_t

(请注意,这取决于设置的标志 _ATL_CSTRING_EXPLICIT_CONSTRUCTORS。如果没有设置标志,构造函数不是显式的,但是选择哪个构造函数就很模糊了。)

因此,您需要根据需要将参数显式转换为charwchar_t

CStringA str = CStringA(static_cast<char>('A' + 5));

或:

CStringW str = CStringW(static_cast<wchar_t>(L'A' + 5));

【讨论】:

    【解决方案2】:

    CString 不会将 int 隐式转换为 CString。不过你可以这样尝试

    CString str; 
    char c = 'A';
    int i = 5;
    str.Format(L"%c%d",c, i);  // unicode assumed
    

    【讨论】:

      猜你喜欢
      • 2010-10-08
      • 2011-11-02
      • 1970-01-01
      • 1970-01-01
      • 2012-05-08
      • 1970-01-01
      • 2013-02-04
      • 1970-01-01
      • 2023-03-16
      相关资源
      最近更新 更多