问题描述
这是我的构造函数。
SceneContainer::SceneContainer()
:
m_BVH(Allshapes,0)
{
ParseJSONDataIntoShapeData("ShapeList.json");
}
这里是场景类声明。
class SceneContainer{
public:
void ParseJSONDataIntoShapeData(std::string filename);
private:
BVHNode m_BVH;
std::vector<shape*> Allshapes;
};
{
"scene": {
"shape": [{
"center": "1.0 1.0 1.0","radius": 1,"_name": "sphere1","_type": "sphere"
},{
"center": "2.0 2.0 2.0","_name": "sphere2",{
"center": "3.0 3.0 3.0","_name": "sphere3","_name": "sphere4","_type": "sphere"
}]
}
parseJSONDataIntoShapeData 然后将遍历文件中的所有形状并 push_back 一个指向在文件中创建的形状的指针。一些伪代码看起来像这样。
for(all shapes in json file)
Create shape pointer from shape data
push_back shape pointer to AllShapes.
在调用 parseJSONdata 之后,Allshapes 向量中有四个形状。然而,由于构造函数如何与我的原始实现一起工作,m_BVH 被初始化为一个空向量,因为 ParseJSONData 在 m_BVH 初始化后被调用,而我希望它使用其中的形状数据进行初始化。
解决方法
因此,您有一些分配给类成员的函数。但是您还有该类的另一个成员,它将使用第一个成员的内容。
您应该拥有一个函数,它返回用于初始化第一个成员的数据,然后您可以将其用作第二个成员的构造函数的一部分:
class SceneContainer{
public:
//Doesn't set data into the object.
static std::vector<shape*> ParseJSONDataIntoShapeData(std::string filename);
//Setting the data into the object is a separate step.
void ResetJSONDataIntoShapeData(std::string filename)
{
//Free Allshapes;
Allshapes = ParseJSONDataIntoShapeData(filename);
m_BVH.reassign(Allshapes,0); //Tells the m_BVH object that its data has changed.
}
private:
std::vector<shape*> Allshapes;
BVHNode m_BVH;
};
SceneContainer::SceneContainer()
: Allshapes(ParseJSONDataIntoShapeData("ShapeList.json")),m_BVH(Allshapes,0)
{}
请注意,Allshapes
和 m_BVH
的声明顺序已更改。这很重要,因为这些对象的声明顺序将决定它们初始化的顺序。