我有一個特定的情況,我有一個對象,我想使用boost隨機數生成器,並且它導致了一個更大的問題我似乎無法回答。以下是我試圖製作的示例代碼。在C++中使用非缺省構造函數初始化一個對象的成員類
首先,我的頭:
Class MyObject {
protected:
double some variable;
boost::random::mt19937 rgenerator;
boost::uniform_real<double> dist_0_1;
boost::variate_generator< boost::mt19937&, boost::uniform_real<double> > rand01
}
現在我想做的是:
Class MyObject {
protected:
double some variable;
boost::random::mt19937 rgenerator(std::time(0)); //initialize to a "random" seed
boost::uniform_real<double> dist_0_1(0,1); //set the distribution to 0-1
boost::variate_generator< boost::mt19937&, boost::uniform_real<double> > rand01(rgenerator, dist_0_1);//tell it to use the above two objects
}
但是,這並不工作,因爲它是在一個頭。我想我可以使用MyObject的構造函數以某種方式調用各種子對象(分佈,生成器)上的構造函數,但我無法弄清楚,在調用MyObject的構造函數時,子對象的默認值構造函數已經被調用,我還沒有發現他們有成員方法來重置這些屬性......除此之外,這不是我困惑的地方,現在可能有太多的事情在發生,米混亂的問題,但據我所知,我的問題減少到下方,幼稚例如:
Class Tree {
Tree();
Tree(int);
protected:
fruit apples(int);
}
Tree::Tree() {
apples(0); //won't work because we can't call the constructor again?
}
Tree::Tree(int fruit_num) {
apples(fruit_num); //won't work because we can't call the constructor again?
}
Class Fruit {
public:
Fruit();
Fruit(int);
protected:
int number_of_fruit;
}
Fruit::Fruit() {
number_of_fruit = 0;
}
Fruit::Fruit(int number) {
number_of_fruit = number;
}
我敢肯定,這是第二個性質所有人都在那裏,但我不能找到一個討論將對象的成員對象初始化爲非默認構造函數值的最佳實踐的文章
+1解釋其他可能性。爲了完整性,您還可以指定基類的名稱(以使用非默認的基類構造函數)或(在C++ 11中)指定當前類的名稱(以使用構造函數委派)。 –
感謝大家建議的初始化程序列表。這是問題。我曾看過他們使用過,但只是平凡......所以我從來沒有拿起他們的實際使用!他們解決了這個問題! – Avacar