【发布时间】: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& operator=( CharT ch );不应该是explicit?也就是说,为什么允许s = 97?s是字符串,那为什么要隐式转换给它赋值呢?这种
s = 97隐式转换可以避免/停止吗?
还有,一些附带的问题:这段代码用g++编译得很好,但用clang编译不出来,它会报这个错误:
error: expected ';' at end of declaration
std::string s{"someThing"};
^
那么,为什么g++能编译这个而clang不能呢?
编辑:感谢 Edgar Rokyan,现在它可以使用带有 -std=c++11 选项的 clang++ 进行编译。
编辑:所以,根据 Edgar Rokyan 和 MSalters 的回答,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