使用< random>在C ++类中 [英] Use <random> in a c++ class
问题描述
我想在程序中使用< random>
库,并且我将拥有具有不同分布的类,并且我想在程序中的不同时间生成一个数字.当前,我的头文件中有以下内容
I want to use the <random>
library in my program and I will have classes with different distributions and I want to generate a number at different times in my program. Currently I have the following in my header file
#include <random>
#include <time.h>
class enemy {
private:
int max_roll;
typedef std::mt19937 MyRng;
MyRng rng;
public:
enemy(int MR){
max_roll = MR;
rng.seed(time(NULL));
std::uniform_int_distribution<int> dice(1, max_roll);
}
int roll() {
return dice(rng);
}
};
我遇到的问题是"dice"未定义,即使它在我的构造函数中也是如此.当我将分布定义移动到roll函数的开头时,它将起作用,但是当我这样做时,每次调用它都会得到相同的数字.我已尝试按照上的答案进行操作>这个问题,但我无法解决.
I'm getting the issue with 'dice' being undefined even though it's in my constructor there. It will work when I move my distribution definition to the beginning of my roll function, but when I do that, I get the same number every time I call it. I've tried following the answer on this question, but I couldn't work it out.
推荐答案
正如drescherjm指出的那样,dice是变量中的局部变量.您需要使它在ctor范围之外可以访问.我试图在这里重新设计您的程序.我认为您想要的是一个随机数生成器,该生成器可以生成从0到MR的整数值?在这种情况下,您可以使用下面重新设计的程序:
As drescherjm pointed out, dice is a local variable within he ctor. You need to make it accessible outside the scope of the ctor.I have tried to rework your program here. I think what you want is a random number generator that generates integer values from 0 to MR ? If that is the case, you can use the reworked program below:
#include <random>
#include <time.h>
#include <iostream>
class enemy {
private:
std::random_device rd;
int max_roll;
typedef std::mt19937 MyRng;
MyRng rng;
std::uniform_int_distribution<int> dice;
public:
enemy(int MR) : max_roll(MR), rng(rd()), dice(std::uniform_int_distribution<>(1, MR)){
rng.seed(::time(NULL));
}
int roll() {
return dice(rng);
}
};
int main()
{
enemy en(6);
std::cout << "Roll dice produced : " << en.roll() << std::endl;
return 0;
}
该程序不言自明.如果不是这样的话,请告诉我,我可以带您完成.
The program is self-explanatory. Please let me know if it is not and I can take you through it.
这篇关于使用< random>在C ++类中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!