Ant*_*nko 3 c c++ arrays struct
我在 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)
}};
}
Run Code Online (Sandbox Code Playgroud)
当我尝试在 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
}};
Run Code Online (Sandbox Code Playgroud)