我目前正在实现代表52张牌的Deck类。它使用boost随机库对表示卡的整数进行混洗。
#include <iostream>
#include <fstream>
#include "constants.hpp"
#include <boost/program_options.hpp>
#include <vector>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int.hpp>
#include <boost/random/variate_generator.hpp>
boost::mt19937 gen(std::time(0));
class Deck{
private:
std::vector<int> cards;
int cardpointer;
static ptrdiff_t choosecard(ptrdiff_t i);
ptrdiff_t (*pchoosecard)(ptrdiff_t);
public:
Deck();
void shuffle();
int pop();
};
Deck::Deck(){
for(int i=1; i<=52; i++){
cards.push_back(i);
}
cardpointer = -1;
pchoosecard = &choosecard;
}
ptrdiff_t Deck::choosecard(ptrdiff_t i){
boost::uniform_int<> dist(0,i);
boost::variate_generator< boost::mt19937&, boost::uniform_int<> > cardchoice(gen, dist);
return cardchoice();
}
void Deck::shuffle(){
std::random_shuffle(cards.begin(), cards.end(), pchoosecard);
}
我想移动“boost::mt19937 gen(std::time(0));”行是类的一部分,但是我遇到了问题,因为当我将其移到类定义中时遇到此错误:
$ make
g++ -I /usr/local/boost_1_45_0/ -c main.cpp
main.cpp:22: error: ‘std::time’ is not a type
main.cpp:22: error: expected ‘)’ before numeric constant
main.cpp:22: error: expected ‘)’ before numeric constant
main.cpp:22: error: expected ‘;’ before numeric constant
main.cpp: In static member function ‘static ptrdiff_t Deck::choosecard(ptrdiff_t)’:
main.cpp:39: error: ‘gen’ was not declared in this scope
make: *** [main.o] Error 1
最佳答案
如果要使其成为普通的类变量,请在构造函数中对其进行初始化:
class Deck {
...
public:
boost::mt19937 gen;
};
Deck::Deck() : gen(std::time(0))
{
...
}
如果您将其设为静态(看起来像是静态的,因为您使用的是
gen
中的choosecard
,它是静态的),则您仍需要在类外进行声明:class Deck {
...
public:
static boost::mt19937 gen;
};
boost::mt19937 Deck::gen(std::time(0));
关于c++ - 将RNG隐藏在类中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4356498/