我的问题在代码中,但基本上我想知道如何/是否可以执行这两行注释掉的代码?我知道我可以在构造函数中完成,但我不想这样做!
struct foo
{
int b[4];
} boo;
//boo.b[] = {7, 6, 5, 4}; // <- why doesn't this work? (syntax error : ']')
//boo.b = {7, 6, 5, 4}; // <- or else this? (syntax error : '{')
boo.b[0] = 7; // <- doing it this way is annoying
boo.b[1] = 6; // :
boo.b[2] = 5; // :
boo.b[3] = 4; // <- doing it this way is annoying
boo.b[4] = 3; // <- why does this work!
(使用:C++、Visual Studio 2005。)
最佳答案
只能在定义中使用初始化:
struct foo
{
int b[4];
};
foo boo = { 7, 6, 5, 4 };
关于最后一个问题:“为什么 boo.b[4] = 3
有效?”答案是它是未定义的行为,并且 UB 允许相当多的不同情况。编译器和运行时环境都不必对其进行诊断,在许多情况下,结果将覆盖内存中的下一个元素。可以使用以下代码进行测试:
// Test
foo boo;
int x = 0;
boo.b[4] = 5;
std::cout << x << std::endl;
注意:这是未定义的行为,因此无论测试结果如何,它都是不正确的,不能假定为可重复的测试。
关于c++ - 如何在不单独执行每个元素的情况下初始化结构内的数组? (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2835393/