【问题标题】:Expression must be modifiable ivalue for struct表达式必须是结构的可修改值
【发布时间】:2020-02-23 08:33:29
【问题描述】:
struct Vertex
{
    float Position[3];
    float Color[4];
    float TextCoords[2];
    float TexId;
};

static std::array<Vertex, 4> CreateQuad(float x, float y) {
    Vertex v;
    v.Position = { 0.0f,0.0f,0.0f };
}

这给了我一个错误,即 v 必须可修改的 ivalue。以及太多的初始化值。

【问题讨论】:

  • Vertex v{}; 将实现目标

标签: c++ arrays struct compiler-errors syntax-error


【解决方案1】:

你不能用初始化列表分配一个普通数组,但你可以这样分配一个std::array

struct Vertex
{
    std::array<float, 3> Position;
    std::array<float, 4> Color;
    std::array<float, 2> TextCoords;
    float TexId;
};

 static std::array<Vertex, 4> CreateQuad(float x, float y) {
    std::array<Vertex, 4> v;    
    v[0].Position = { 0.0f, 0.0f, 0.0f };
    // fill the rest of v...
    return v;
}

【讨论】:

  • 这样使用 std::array 是否有性能成本。还有我只是从这个youtu.be/5df3NvQNzUs?t=991 视频中复制的。
  • @Krinjon 不,没有额外费用。 std::array 只是一个普通数组 + 一些方便的辅助函数。
  • 并且带有纯数组的代码在该视频中有效。 .
  • @Krinjon 可能是编译器扩展。你知道他们使用什么编译器吗?
  • @TedLyngmo :对此感到抱歉,实际上他将数组更改为 vec3。但由于他没有得到任何错误的直线,我认为他运行得很好。可能关闭了视觉工作室中的 sqwiglies。他后来在视频中构建它时确实出错了。
【解决方案2】:

您不能将数组分配给初始值设定项列表。这就是您收到错误的原因:

错误:从初始化列表分配给数组

但是,您可以将std::initializer_list 传递给您的构造函数并将其成员复制到普通数组,例如:

Vertex(std::initializer_list<float> const& position) {
    std::copy(position.begin(), position.end(), Position);
}

然后像Vertex v({ 0.0f,0.0f,0.0f });一样初始化。

不过,我建议您使用std::array 而不是普通数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-09
    • 2011-08-25
    • 2019-06-28
    • 2020-07-07
    • 2017-08-27
    • 1970-01-01
    • 2021-09-17
    相关资源
    最近更新 更多