![](/img/trans.png)
[英]Can class member be initialized with another class member in the initializer list?
[英]I need to call a void function in the middle of a constructors member initializer list so that other objects can be initialized correctly
這是我的構造函數。
SceneContainer::SceneContainer()
:
m_BVH(Allshapes, 0)
{
ParseJSONDataIntoShapeData("ShapeList.json");
}
這里是場景 class 聲明。
class SceneContainer{
public:
void ParseJSONDataIntoShapeData(std::string filename);
private:
BVHNode m_BVH;
std::vector<shape*> Allshapes;
};
所以給定一個像這樣的 JSON 文件。
{
"scene": {
"shape": [{
"center": "1.0 1.0 1.0",
"radius": 1,
"_name": "sphere1",
"_type": "sphere"
},
{
"center": "2.0 2.0 2.0",
"radius": 1,
"_name": "sphere2",
"_type": "sphere"
},
{
"center": "3.0 3.0 3.0",
"radius": 1,
"_name": "sphere3",
"_type": "sphere"
},
{
"center": "3.0 3.0 3.0",
"radius": 1,
"_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 初始化之后被調用,而我希望它使用其中的形狀數據進行初始化。
所以,你有一些 function 分配給 class 的成員。 但是您還有另一個 class 成員,它將消耗第一個成員的內容。
您應該擁有的是一個 function ,它返回用於初始化第一個成員的數據,然后您可以將其用作第二個成員的構造函數的一部分:
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
的聲明順序已更改。 這很重要,因為聲明這些對象的順序將決定它們的初始化順序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.