gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:23:28 25 4
gpt4 key购买 nike

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

首先,我的标题:

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 的构造函数时,子对象的默认值构造函数已经被调用,我还没有发现它们有成员方法来重置这些属性……除此之外,这不是我感到困惑的地方。现在也许发生了太多事情,我m 令人困惑的问题,但据我所知,我的问题归结为以下幼稚的示例:

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;

}

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

最佳答案

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

Tree::Tree(int fruit_num) 
: apples(fruit_num) // Initializes "apple" with "fruit_num"
{
}

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

Tree::Tree(int fruit1, int fruit2) : apples(fruit1), bananas(fruit2) {
}

关于c++ - 在 C++ 中使用非默认构造函数初始化对象的成员类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7507526/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com