gpt4 book ai didi

c++ - 现在允许为 std::string 分配一个数字吗?

转载 作者:IT老高 更新时间:2023-10-28 22:58:50 25 4
gpt4 key购买 nike

考虑以下代码片段:

#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>

问题:

  1. 为什么代码片段会编译?
  2. 注释掉 foo = -1,我得到了正确的标准输出(12)。编译器使用 foo = -1; 编译导致后续 cout 失败的原因是什么?

最佳答案

foo = -1;

解析为 std::string::operator=(char)自从 -1intint理论上可以转换为 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com