【问题标题】:Append an integer to std::wstring gives an error将整数附加到 std::wstring 会产生错误
【发布时间】:2017-07-12 23:41:03
【问题描述】:

所有,

我正在使用 MSVC 2010,但主题有问题。

使用以下代码:

int GetValue() {return m_int;};

std::wstring temp += std::to_wstring( GetValue() );

给出一个错误:

ambiguous call to overloaded function
1>          c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\string(771): could be 'std::wstring std::to_wstring(long double)'
1>          c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\string(762): or       'std::wstring std::to_wstring(_ULonglong)'
1>          c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\string(753): or       'std::wstring std::to_wstring(_Longlong)'
1>          while trying to match the argument list '(int)'

使用以下代码:

ostringstream ostr;
ostr << GetValue();
std::wstring temp += ostr.str();

给出以下错误:

error C2679: binary '+=' : no operator found which takes a right-hand operand of type 'std::basic_string<_Elem,_Traits,_Ax>' (or there is no acceptable conversion)

我哪里错了?

谢谢。

【问题讨论】:

  • 我很确定第一种情况是编译器/标准库错误;这应该工作
  • 这可能不是编译器/库错误。在 ASCII 字符转换到宽字符转换之间没有隐式转换是有原因的。或者一串个字符到一串个字符。
  • 如果你试图追加到一个现有的字符串,为什么你在那一行有类型声明?这声明了一个新变量。
  • 您应该尝试更新版本的 VC++。由于std::to_wstring是在C++11中加入的,所以VC2010支持不完整也就不足为奇了。
  • @BenVoigt,自动补全确实在 IDE 中显示了他的功能。

标签: c++ visual-studio-2010 wstring


【解决方案1】:

常规的std::ostringstream 不宽。 wstring 想要分配一个宽字符串。

你需要std::wostringstream

【讨论】:

    【解决方案2】:

    您不能在变量声明中使用复合赋值。

    引入初始化器的= 不是赋值运算符,它是声明语法的一部分。您不能替换某些看似相关的标记。

    如果要初始化变量,使用简单的=

    std::wstring temp = std::to_wstring( GetValue() );
    

    如果要进行复合赋值,请在声明后的单独语句中进行:

    std::wstring temp;
    temp += std::to_wstring( GetValue() );
    

    【讨论】:

      猜你喜欢
      • 2014-03-06
      • 2011-08-03
      • 1970-01-01
      • 2012-05-02
      • 2019-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-31
      相关资源
      最近更新 更多