在C和C++中初始化结构中的数组

Array-in-struct initialization in C and C++

本文关键字:结构 数组 初始化 C++      更新时间:2023-10-16

我在C中有以下代码,可以很好地使用

typedef struct { float m[16]; } matrix;
matrix getProjectionMatrix(int w, int h)
{
float fov_y = 1;
float tanFov = tanf( fov_y * 0.5f );
float aspect = (float)w / (float)h;
float near = 1.0f;
float far = 1000.0f;
return (matrix) { .m = {
[0] = 1.0f / (aspect * tanFov ),
[5] = 1.0f / tanFov,
[10] = -1.f,
[11] = -1.0f,
[14] = -(2.0f * near)
}};
}

当我尝试在C++中使用它时,我会得到以下编译器错误:error C2143: syntax error: missing ']' before 'constant'

为什么会这样?将代码移植到C++的最简单方法是什么?

您正试图使用指定的初始值设定项,这在C中是允许的,但在C++中是不允许的。

您需要显式初始化各个成员:

return (matrix) { {
1.0f / (aspect * tanFov ),
0, 0, 0, 0,
1.0f / tanFov,
0, 0, 0, 0,
-1.f,
-1.0f,
0, 0,
-(2.0f * near),
0
}};