随机数同类初始化 [英] Random Number In-Class Initialisation
问题描述
我目前正在创建一个类,我希望每次创建对象时,使用随机数来初始化其中一个私有成员。以下代码不会产生问题:
I am currently making a class for which I'd like one of the private members to be initialised with a random number each time the object is created. The following code causes no problem:
private:
unsigned random = rand() % 10;
然而,我想使用C ++ 11随机引擎和发行版。我想能够按照下面的代码行,它不会编译,但会提供一个大致的想法,我想做的事情:
I would, however, like to use the C++11 random engines and distributions to do this. I would like to be able to do something along the lines of the following code, which will not compile but will give a general idea of what I'm trying to do:
private:
unsigned random = distribution(mersenne_generator(seed));
static std::random_device seed_generator;
static unsigned seed = seed_generator(); //So that it's not a new seed each time.
static std::mt19937 mersenne_generator;
static std::uniform_int_distribution<unsigned> distribution(0, 10);
此代码将无法编译,因为我想在类中定义一些静态成员。我不知道在哪里定义它们,但是。我可以创建一个成员函数初始化一切,但然后我必须在main中运行它,我不想。我想只是整理出所有的随机定义在类中,所以当我在main中创建一个对象,它将隐式创建的随机数。任何建议?
This code won't compile because I'm trying to define some of the static members in the class. I'm not sure where to define them, however. I could create a member function that initialises everything, but then I would have to run it in main, which I don't want to. I would like to just sort out all the random definitions in class so that when I create an object in main, it will create the random number implicitly. Any suggestions?
推荐答案
您需要在类定义之外定义静态数据成员。例如,这将工作:
You need to define the static data members outside the class definition. For instance, this will work:
struct foo
{
private:
unsigned random = distribution(mersenne_generator);
static std::random_device seed_generator;
static unsigned seed;
static std::mt19937 mersenne_generator;
static std::uniform_int_distribution<unsigned> distribution;
};
std::random_device foo::seed_generator;
unsigned foo::seed = seed_generator();
std::uniform_int_distribution<unsigned> foo::distribution(0, 10);
std::mt19937 foo::mersenne_generator(foo::seed);
静态数据成员的定义应放在.cpp文件中,否则运行风险违反了一个定义规则。
The definitions for the static data members should be placed in a .cpp file, else you run the risk of violating the one definition rule.
这篇关于随机数同类初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!