我目前在带有 C(非 C++)和 OpenGL 的 win7 64 位上使用 VS2008 Express。拥有这个我已经编码了一段时间的软件 3d 引擎,是时候从文件中加载对象了。最大的变化是从结构内的静态数组(完成并除尘)转移到结构内的动态数组(痛苦)。
结构如下:
// the structure for handling an object
struct ObjectHolder
{
int iVertexCount; //number of vertices of object being loaded
//float fVerticeStore[48]; //actual vertex data read from file
//changing to dynamic
//this works but is not scalable
//my dynamic array test
float *fpVerticeStore = NULL; //should be dynamic
};
好的,那么我有一个在初始化引擎时调用的函数。
- 它实例化结构
- 打开保存对象数据的文件
- 然后将数据读入动态数组
- 沿途测试任意错误
void weLoad_file_objects_to_memory()
{
int i = 0;
ifstream indata; // nuf said
int num1, num2, num3; // variables to hold vertex data
char tag[2]; // tag holds the abbreviation of the data type being loaded
//such as vc = vertexcount, v = vertex, l = line
//mildly similar to .obj format
indata.open("construct.dat"); // opens the file
if(!indata)
{ // file couldn't be opened
cerr << "Error: file could not be opened" << endl;
exit(1);
}
struct ObjectHolder weConstructObject; //struct instantiated here
indata >> tag; //tag simply tests for type of data in file
if ( tag == "vc")
{
indata >> weConstructObject.iVertexCount;
//set size of dynamic array ie: the Vertex Store
//first try using "new" does not work
//weConstructObject.fpVerticeStore = new int[weConstructObject.iVertexCount];
//second try using malloc does not work
weConstructObject.fpVerticeStore = (float*) malloc(32 * sizeof(float));
}
else
{
MessageBox(NULL,"Vertex Count Error!","VERTEX COUNT ERROR",MB_OK|MB_ICONEXCLAMATION);
//break;
}
//read in vertex data from file
while ( !indata.eof() )
{ // keep reading until end-of-file
indata >> tag >> num1 >> num2 >> num3;
if (tag == "v")
{
weConstructObject.fpVerticeStore[i++] = float(num1);
weConstructObject.fpVerticeStore[i++] = float(num2);
weConstructObject.fpVerticeStore[i++] = float(num3);
}
else
{
MessageBox(NULL,"Vertex Store Error!","STORE ERROR",MB_OK|MB_ICONEXCLAMATION);
//break;
}
}
indata.close();
//cout << "End-of-file reached.." << endl;
//return 0;
}
在关闭发动机时,以下内容适用
// Delete all dynamic arrays
delete [] weConstructObject.fpVerticeStore; // When done, free memory pointed to.
weConstructObject.fpVerticeStore = NULL; // Clear to prevent using invalid memory reference.
构造.dat 看起来像
vc 16
v -20 0 20
v -10 0 20
...
这个问题有很多版本,非常混乱。我喜欢保持我的代码简单。谁能弄清楚我为什么会出现编译错误?
only static const integral data members can be initialized within a class