【问题标题】:Array-in-struct initialization in C and C++C 和 C++ 中的 Array-in-struct 初始化
【发布时间】:2020-11-01 08:07:03
【问题描述】:

我有以下 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++ 的最简单方法是什么?

【问题讨论】:

  • Designated Initializers 已添加到 C++ 20 标准修订版中,但我认为它们不允许像那样初始化数组。添加构造函数有意义吗?
  • 您是否需要将此文件编译为 C++?也许您可以将其编译为 C,而将应用程序的其余部分保留为 C++。我对代码库的某些部分执行此操作,并且效果很好。
  • @rturrado 所以它是重复的 :( 抱歉,我搜索过但没有看到那个
  • @Anton Duzenko 没有问题,你总能得到一些新奇有趣的 cmets 和答案????

标签: c++ arrays c struct


【解决方案1】:

您正在尝试使用 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
  }};

【讨论】:

    猜你喜欢
    • 2016-02-08
    • 1970-01-01
    • 2021-03-19
    • 2011-07-29
    • 2021-09-21
    • 2017-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多