2014-04-09 74 views
0

我有類似如下:構建對象在另一個類變量初始化後

QuadMesh.h:

#include "StructureIpsim.h" // this is a struct 

class QuadMesh { 

public: 
QuadMesh(StructureIpsim s) {//do stuff} 

}; 

SEMPotential.h:

#include "QuadMesh.h" 
#include "SpecialFuncs.h" 

class SEMPotential { 

public: 
StructureIpsim SI; 
QuadMesh mesh; 
SEMPotential(//args); 

}; 

SEMPotential::SEMPotential(//args) { 
// init structure in here, need to call functions from SpecialFuncs.h to do so 
// How to construct the QuadMesh object mesh? Can't put in initialization list. 
} 

正如你所看到的, QuadMesh對象需要一個StructureIpsim sruct,但是在傳遞之前,必須使用SEMPotential的構造函數中的幾個函數來初始化此結構到QuadMesh構造函數。這是什麼標準的方法?

+0

一個好的設計是'StructureIpsim'通過它的構造函數正確設置(它的參數是通過構造函數初始化列表從'SEMPotential'的構造函數提供的) –

+0

如果這是不可能的,可以使'mesh通過使用'std :: shared_ptr '來延遲構建,而不是在你準備好之前你不分配它。 –

+0

另一種選擇是'QuadMesh'有一個默認的構造函數,它什麼都不做,並且你準備好了一個函數來在你準備好之後進行設置 –

回答

1

CAN使用初始值設定項列表。使用一個輔助函數,該函數可能應該是一個私有靜態成員函數,它接受相關的參數,進行計算並返回一個QuadMesh對象。使用初始化列表從該助手的返回值初始化成員。

class SEMPotential 
{ 
    static QuadMesh mesh_creator(/* args */); 
public: 
    QuadMesh mesh; 
    SEMPotential(/* args */) : mesh(mesh_creator(args)) {} 
}; 

QuadMesh SEMPotential::mesh_creator(/*args*/) 
{ 
    StructureIpsum s; 
    // init structure in here, calling functions from SpecialFuncs.h to do so 
    return QuadMesh(s); 
} 

馬特麥克納布在他的評論中指出,該助手功能可能StructureIpsum的構造函數。但是我提出了一個不需要修改StructureIpsumQuadMesh類定義的解決方案。

如果您想保留StructureIpsum實例,使用輔助方法技巧進行初始化,然後簡單地使用它來初始化網:

SEMPotential(/* args */) : SI(ipsum_creator(args)), mesh(SI) {} 
成員

初始化爲了保證(這是他們的順序出現在類中,初始化列表中的排序不起作用)。

+0

很酷,這似乎工作。爲什麼靜態? – bcf

+0

@bcf:因爲輔助函數在存在「SEMPotential」實例之前調用(它仍在創建中)。 –

+0

Gotcha。感謝您的快速解決! – bcf