我目前正在实施一个代表52张牌的甲板课程。它使用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));” line是该类的一部分,但是我遇到了这样的问题,因为当我将它移到类定义中时会出现这个错误:
$ 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
答案 0 :(得分:4)
如果你使它成为普通的类变量,请在构造函数中初始化它:
class Deck {
...
public:
boost::mt19937 gen;
};
Deck::Deck() : gen(std::time(0))
{
...
}
如果你是静态的(它看起来像你,因为你正在使用来自gen
的{{1}},这是静态的),你仍需要在课外进行声明:
choosecard
答案 1 :(得分:2)
根据我的想法,这是猜测。您必须将定义与静态gen
成员的初始化分开:
class Deck {
static boost::mt19937 gen;
// ...
};
boost::mt19937 Deck::gen(std::time(0));
答案 2 :(得分:0)
class Deck{
boost::mt19937 gen;
...
};
Deck::Deck(): gen(std::time(0)){
...
}
Deck::Deck(uint32_t seed): gen(seed){
...
}