現在、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.
construct.dat は次のようになります
vc 16
v -20 0 20
v -10 0 20
...
この問題には非常に多くのバージョンがあり、非常に混乱しています。コードをシンプルにするのが好きです。コンパイルエラーが発生する理由を誰かが理解できますか?
only static const integral data members can be initialized within a class