考虑以下代码片段:
#include <iostream>
int main() {
std::string foo;
foo = -1; // why is the compiler not complaining about this?
std::cout << "1" << std::endl;
std::cout << foo << std::endl;
std::cout << "2" << std::endl;
}
实际输出(ideone.com C++14模式和GCC 4.8.4):
<no output>
问题:
- 为什么代码片段会编译?
- 注释掉
foo = -1
,我得到了正确的标准输出(1
和2
)。编译器使用foo = -1;
编译导致后续cout
失败的原因是什么?
最佳答案
foo = -1;
解析为 std::string::operator=(char)
自从 -1
是 int
和 int
理论上可以转换为 char
.
我不清楚标准在 int
时的含义。不代表有效的 char
.看起来在您的实现中,程序崩溃了。
更新
来自 C++11 标准(重点是我的):
3.9.1 Fundamental types
1 Objects declared as characters (
char
) shall be large enough to store any member of the implementation’s basic character set. If a character from this set is stored in a character object, the integral value of that character object is equal to the value of the single character literal form of that character. It is implementation-defined whether a char object can hold negative values.
看来您必须查阅编译器的文档才能了解它是否允许 char
对象来保存负值,如果是,它如何处理这些对象。
关于c++ - 现在允许为 std::string 分配一个数字吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37202036/