2

我想知道如何将 mersenne 随机数生成器保留为成员变量并在同一个类中使用它。

我编写了如下的类,它运行良好,但我不喜欢std::mt19937初始化的类。我想知道是否有办法在构造函数中初始化它Test

#include <iostream>
#include <cmath>
#include <random>
#include <chrono>
#include <ctime>

class Test{
public:
    Test()
    {

    }
    void foo()
    {
        auto randomNum = std::uniform_int_distribution<>(0, threads.size())(rnd);
    }

private:
    std::mt19937 rnd
    {
        std::chrono::high_resolution_clock::now().time_since_epoch().count()
    };
}
4

1 回答 1

4

我认为您对类中初始化的确切作用感到困惑。当你有

struct foo
{
    foo() {}
    int bar = 10;
};

类初始化只是语法糖

struct foo
{
    foo() : bar(10) {}
    int bar;
};

每当编译器将成员添加到成员初始化程序列表时(当您忘记它或编译器提供构造函数时完成)它使用您在初始化中使用的内容。所以用你的代码

class Test{
public:
    Test()
    {

    }
    void foo()
    {
        auto randomNum = std::uniform_int_distribution<>(0, threads.size())(rnd);
    }

private:
    std::mt19937 rnd
    {
        std::chrono::high_resolution_clock::now().time_since_epoch().count()};
    };
};

变成

class Test{
public:
    Test() : rnd(std::chrono::high_resolution_clock::now().time_since_epoch().count())
    {

    }
    void foo()
    {
        auto randomNum = std::uniform_int_distribution<>(0, threads.size())(rnd);
    }

private:
    std::mt19937 rnd;
};

没有实际这样做并使用你一开始的做法的好处是你不必重复

rnd(std::chrono::high_resolution_clock::now().time_since_epoch().count())

在您编写的每个构造函数中,但如果您想要特定构造函数的其他内容,则始终可以覆盖它。

于 2017-01-25T15:35:34.383 回答