【发布时间】:2019-11-05 15:26:39
【问题描述】:
我正在尝试像这样用 0 初始化一个对象数组(更复杂项目的简化代码):
#include <iostream>
struct Vector {
float s[4];
Vector() {}
static Vector zero() {
Vector v;
v.s[0] = 0;
v.s[1] = 0;
v.s[2] = 0;
v.s[3] = 0;
return v;
}
};
struct Test {
Vector v[4] = { Vector::zero() };
};
int main(int argc, char** argv)
{
Test t;
for (int i = 0; i < 4; i++) {
printf("%f %f %f %f\n", t.v[i].s[0], t.v[i].s[1], t.v[i].s[2], t.v[i].s[3]);
}
return 0;
}
此代码应打印全 0,但有时会打印不同的值。看起来只有数组的第一个元素被初始化。但是如果我写 float x[4] = { 0 },那么数组 x 的所有元素都用 0 初始化。有什么区别,我可以在 C++ 标准的什么地方了解这种行为?
【问题讨论】:
-
使 s 全局化,它的元素将被初始化为 0
-
@Cornstalks 谢谢,我修好了,但没有改变根本问题。
-
@QuentinUK 谢谢,我知道,但我不能这样做 :-)
-
我有点困惑。如果您对未提及标准的答案感到满意,您为什么要求参考标准?
-
如果是 std::array
教练应该强迫你使用而不是阻止,恕我直言,我会更高兴。
标签: c++ language-lawyer