【问题标题】:Ambigous integer assignment to string c++字符串c ++的模糊整数赋值
【发布时间】:2017-12-01 09:55:57
【问题描述】:

所以,在玩 C++ 时,我这样做了:

#include <iostream>

int main() {

  std::string s{"someThing"};

  std::cout << "  s is: " << s << '\n';

  s = 97;

  std::cout << "  s is: " << s << '\n';

  return 0;
}

当我用 g++ 编译时,编译完美,运行时输出如下:

  s is: someThing
  s is: a

但我的疑问是为什么编译正确?

然后我发现这个 SO question 解决了这个问题:

Why does C++ allow an integer to be assigned to a string?

然后我从 C++ 中找到了这个documentation

basic_string& operator=( CharT ch );

所以,我的主要问题是:

  • basic_string&amp; operator=( CharT ch ); 不应该是explicit?也就是说,为什么允许s = 97s是字符串,那为什么要隐式转换给它赋值呢?

  • 这种s = 97 隐式转换可以避免/停止吗?

还有,一些附带的问题:这段代码用g++编译得很好,但用clang编译不出来,它会报这个错误:

error: expected ';' at end of declaration
std::string s{"someThing"};
                     ^

那么,为什么g++能编译这个而clang不能呢?

编辑:感谢 Edgar Rokyan,现在它可以使用带有 -std=c++11 选项的 clang++ 进行编译。

编辑:所以,根据 Edgar RokyanMSalters 的回答,assignment operator can't be made explicit,好的,但是为什么允许将整数分配给字符串强>?

【问题讨论】:

  • 你说“编译完美”。这是否意味着您甚至没有收到严格配置的警告,例如g++ -Wall 甚至更严格?
  • @Yunnosch 我添加了-Wall 标志,仍然没有警告
  • 它也以clang编译-std=c++11 -Wall -Wextra -Wpedantic,没有任何警告。顺便说一句:97 可以安全地转换为 char。当您将其更改为例如970 然后你会收到警告。

标签: c++ g++ implicit-conversion clang++ stdstring


【解决方案1】:

不应该basic_string&amp; operator=( CharT ch );是explicit

不可能,它不是构造函数或转换函数。

可以避免/停止这种s = 97 隐式转换吗?

不在您的代码中,因为它是定义明确的 C++。

【讨论】:

    【解决方案2】:

    basic_string&amp; operator=( CharT ch ); 不应该是明确的吗?那是, 为什么会这样:s = 97 允许? s 是一个字符串,那为什么要一个 整数被隐式转换赋值给它?

    来自explicit specifier

    显式说明符指定 构造函数或转换 函数(C++11 起) 不允许隐式转换或 复制初始化。它可能只出现在 decl-specifier-seq 中 在其类定义中声明此类函数。

    所以,你不能明确赋值运算符。

    这种s = 97 隐式转换可以避免/停止吗?

    一般来说,不,因为它对于 std::string 是完全合法的。当你打电话时:

    basic_string& operator=( CharT ch );
    

    使用97,然后将类型为int97转换为char并执行operator=

    那么,为什么 g++ 可以编译这个而 clang 不可以呢?

    很可能,您尝试在不支持 C++11 的情况下使用 clang 编译程序。

    【讨论】:

    • 我的错,使用 clang 编译时没有启用 c++11 支持,谢谢 :)
    猜你喜欢
    • 2012-05-24
    • 2012-11-04
    • 2011-09-08
    • 1970-01-01
    • 2016-05-12
    • 2016-04-01
    • 2016-02-18
    • 1970-01-01
    • 2017-08-16
    相关资源
    最近更新 更多