我在 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++ 中使用它时,我得到了这个编译器错误:
错误 C2143:语法错误:在“常量”之前缺少“]”
为什么会这样,将代码移植到 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
}};
关于c++ - C 和 C++ 中的结构中数组初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62853650/