gpt4 book ai didi

c++ - 初始化指向结构的指针 - 编译器警告

转载 作者:太空狗 更新时间:2023-10-29 20:05:04 25 4
gpt4 key购买 nike

#include <iostream>
using namespace std;

struct test
{
int factorX;
double coefficient;
};

int main()
{
test firstTest = {1, 7.5}; //that's ok

test *secondTest = new test;
*secondTest = {8, 55.2}; // issue a compiler warning

}

我不明白为什么编译器会发出以下警告:

test2.cpp:13:33: warning: extended initializer lists only available with -std=c++11 or -std=gnu++11 [enabled by default]
test2.cpp:13:33: warning: extended initializer lists only available with -std=c++11 or -std=gnu++11 [enabled by default]

我知道在 C++11 中我可以省略赋值运算符,但事实并非如此。我正在使用 g++ 4.7.2。

最佳答案

您的测试 结构是一个聚合。在初始化 aggregate 时C++98 支持大括号语法,不支持赋值。

这里,真正发生的是编译器调用隐式生成的移动赋值运算符,该运算符将 test&& 作为其输入。为了使这个调用合法,编译器必须将 {8, 55.2} 转换为 test 的实例,方法是从它构造一个临时对象,然后移动赋值 *secondTest 来自这个临时的。

此行为仅在 C++11 中受支持,这就是编译器告诉您必须使用 -std=c++11 选项进行编译的原因。

关于c++ - 初始化指向结构的指针 - 编译器警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15524100/

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