如果使用 VC++ 2017 编译,下面的代码将打印垃圾(或零);如果使用 GCC 或 Clang 编译,则打印“1122”( https://rextester.com/JEV81255 )。这是 VC++ 的错误还是我在这里遗漏了一些东西?
#include <iostream>
struct Item {
int id;
int type;
};
int main()
{
auto items = new Item[2]
{
{ 1, 1 },
{ 2, 2 }
};
std::cout << items[0].id << items[0].type;
std::cout << items[1].id << items[1].type;
}
同时,如果元素是原始类型(如int
),它也可以工作。
最佳答案
我通过编写以下代码使其工作,但数据未存储在堆上。
Item items[] {
{ 1, 1 },
{ 2, 2 }
};
如果您在堆上需要它,请使用下面的解决方案,它似乎适用于 vc++ 编译器。 (请注意,这只是一种解决方法,并不能解决根本问题):
Item* Items[2];
Items[0] = new Item{3,3};
Items[1] = new Item{4,4};
std::cout << (*Items[0]).id << (*Items[0]).type << std::endl;
std::cout << (*Items[1]).id << (*Items[1]).type << std::endl;
或者,您可以使用第一个选项创建数组,然后将其复制到堆上的数组中,如下所示:
Item items[2]{
{1,1},
{2,2}
};
Item* hitem = new Item[2];
for(int i = 0; i < 2; i++){
hitem[i].id = items[i].id + 4;
hitem[i].type = items[i].type + 4;
}
虽然这很慢,但它的工作原理甚至在 vc++ 编译器上也是如此。 您可以在此处查看完整代码:https://rextester.com/VNJM26393
我不知道为什么它只能这样工作......
关于c++ - Visual Studio 2019 无法正确处理动态结构数组的聚合初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57786717/