如何初始化结构中的数组而不单独执行每个元素?(C++)

Jan*_*net 2 c++ arrays struct

我的问题在代码中,但基本上我想知道如何/如果我可以做两个注释掉的行?我知道我可以在构造函数中完成它,但我不想!

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!
Run Code Online (Sandbox Code Playgroud)

(使用:C++,Visual Studio 2005.)

Dav*_*eas 8

您只能在定义中使用初始化:

struct foo
{
    int b[4];
};
foo boo = { 7, 6, 5, 4 };
Run Code Online (Sandbox Code Playgroud)

关于最后一个问题:'为什么boo.b[4] = 3有效?' 答案是它是未定义的行为,UB允许相当多的不同情况.编译器和运行时环境都不必诊断它,并且在许多情况下,结果将覆盖内存中的下一个元素.可以使用以下代码测试:

// Test
foo boo;
int x = 0;
boo.b[4] = 5;
std::cout << x << std::endl;
Run Code Online (Sandbox Code Playgroud)

注意:这是未定义的行为,因此无论测试结果如何,都是不正确的,不能认为是可重复的测试.