gpt4 book ai didi

c++ - 此输出有效还是编译器错误?

转载 作者:太空宇宙 更新时间:2023-11-04 15:21:46 24 4
gpt4 key购买 nike

#include <iostream>
#include <string>

int main(int argc, char *argv[])
{
std::string s = {123};
std::cout << s << std::endl;
}

为什么这个程序打印 { 作为输出?它只打印前面的 { 是底层词法分析器中的错误吗?

我用 g++ 4.8.1 编译了它(没有错误或警告)。 MSVC 没有编译这个提示 string 不是聚合类型。

最佳答案

您正在用字符数组对字符串进行列表初始化。 123ASCII code of { .没有编译器错误。

您正在调用的构造函数是 std::string 的初始化列表构造函数(参见 here),如 C++ 的第 21.4.2/15 段所指定11 标准:

basic_string(std::initializer_list<CharT> init, 
const Allocator& alloc = Allocator());

Effects: Same as basic_string(il.begin(), il.end(), a).

MSVC 不支持列表初始化,这就是为什么您会收到提示 string 不是聚合的消息。

关于c++ - 此输出有效还是编译器错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17374683/

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