我想做一些非常简单的事情,但我做错了。
头文件:
class Example
{
public:
typedef struct
{
float Position[3];
float Color[4];
float TexCoord[2];
} IndicatorVertex;
void doSomething();
};
.cpp 文件:
void Example::doSomething()
{
IndicatorVertex *vertices;
vertices = IndicatorVertex[] {
{{-1.0, 1.0, 1.0}, {1.0f, 1.0f, 1.0f, 1.0f}, {0.0f, 0.0f}}
{{1.0, 1.0, 1.0}, {1.0f, 1.0f, 1.0f, 1.0f}, {0.0f, 0.0f}},
};
}
编译后,我收到错误:(12, 13) 意外类型名称 'IndicatorVertex':预期表达式
。
(我故意不使用 std::vector
等;我故意在 c++11 设置中使用 C 功能。)
最佳答案
您不能像这样创建动态数组,您需要定义一个实际的数组,例如
IndicatorVertex vertices[] = { ... };
如果您稍后需要一个指针,请记住数组自然会衰减为指向其第一个元素的指针。因此,例如,如果您想要调用需要 IndicatorVertex*
参数的函数,只需传入 vertices
,它仍然会按预期工作。
如果您想拥有不同的数组并使vertices
指向其中之一,那么您必须如上所示定义数组,并使vertices
指向其中一个其中。喜欢
IndicatorVertex vertices1[] = { ... };
IndicatorVertex vertices2[] = { ... };
// ...
IndicatorVertex* vertices = vertices1;
// ...
vertices = vertices2;
关于c++ - 结构的动态聚合初始化的正确形式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41719193/