c++ - 在类中隐藏 RNG

标签 c++ class boost

我目前正在实现一个代表 52 张牌的牌组的 Deck 类。它使用 boost Random 库来洗牌代表卡片的整数。

#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))
{
    ...
}

如果你让它成为静态的(看起来你是,因为你正在使用 choosecard 中的 gen,它是静态的),你仍然需要一个声明课外:

class Deck {
    ...
    public:
        static boost::mt19937 gen;
};

boost::mt19937 Deck::gen(std::time(0));

关于c++ - 在类中隐藏 RNG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4356498/

相关文章:

c++ - 来自继承类的 Makefile 错误

objective-c - 在 Objective-C 类之间共享代码,例如 PHP 中的 Traits

c++ - 使用 boost over socket 发送和接收压缩文件

c++ - boost::multi_index 用户定义的键提取器和复合键

c++ - 尝试使用 boost::interprocess::message_queue 时出现 library_error 异常

c++ - set 和 multiset 只是一个谓词不同吗?

c++ - 通过 Doxygen 中的宏定义的文档函数

Java:类.this

html - 使用 SSI 在 CSS 导航栏上“选择”按钮

c++ - boost::array of boost::reference_wrapper 未编译