我想将网格的顶点数据存储在一个类中。 每个实例都有一个浮点数数组,可通过返回数组指针的 getter 访问。 数组的数据应该是常量,数组本身也是如此。 所以我的第一个想法是这样声明成员:
const float * const m_vertices; // const pointer to const floats
问题是实际数据在编译时是未知的(从文件加载,程序生成......
有没有办法确保数据在初始化时保持不变(例如在构造函数中(?
编辑: 我尝试了约瑟夫的建议:
//Mesh class
Mesh::Mesh(const float *vertices)
: m_vertices(vertices)
{
}
//creation of data
int size = 10; //this can't be const because the number of vertices is not known at compile time
float arr[size]; //error : "size" is not const
for (int i = 0; i < 10; i++) {
arr[i] = i;
}
Mesh m = Mesh(arr); //this apparently works... But the constructor is expecting a const float *. Here i'm giving a float *. Why does this works ?
您可以使用所需的确切类型。允许构造函数将数据写入const
字段:
class Foo {
public:
const float *const m_vertices;
Foo(const float *vertices) : m_vertices(vertices) {}
};
尽管此处不能保证调用方没有非const
指针。如果要防止这种情况,则需要复制数据,而不仅仅是使用指针。
Mesh::Mesh(const float *vertices): m_vertices(vertices)
{
}
float number = 3.141; // e.g.
int size = 10;
const float *vertices = &number; // e.g.
vertices_ptr = new float[ size ];
meshPtr = new Mesh( vertices_ptr);
通过meshPtr-> ...
访问它