使用C++中的非默认构造函数初始化对象的成员类

Ava*_*car 1 c++ class boost-random class-members

我有一个特定的情况,我有一个对象,我想使用增强随机数生成器,它导致一个更大的问题,我似乎无法回答.这是我正在尝试制作的示例代码.

首先,我的标题:

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
}
Run Code Online (Sandbox Code Playgroud)

现在我想做的是:

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
}
Run Code Online (Sandbox Code Playgroud)

但这不起作用,因为它在标题中.我以为我可以使用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;

}
Run Code Online (Sandbox Code Playgroud)

我确信这是其他所有人的第二天性,但我找不到一篇文章,讨论了将对象的成员对象初始化为非默认构造函数值的最佳实践.

fli*_*ght 6

你想要的是一个初始化列表.例如:

Tree::Tree(int fruit_num) 
    : apples(fruit_num) // Initializes "apple" with "fruit_num"
{
}
Run Code Online (Sandbox Code Playgroud)

您只需:在构造函数参数之后和左大括号之前添加冒号(){.您可以使用逗号(,)分隔不同的成员构造函数.例:

Tree::Tree(int fruit1, int fruit2) : apples(fruit1), bananas(fruit2) {
}
Run Code Online (Sandbox Code Playgroud)

  • +1用于解释其他可能性.为了完整性,您还可以指定基类的名称(使用非默认基类构造函数),或者(在C++ 11中)指定当前类的名称(使用构造函数委派). (2认同)