2

我尝试创建一个具有 default_random_engine 私有字段的类。但是,这个类不能编译。我的简单控制台程序代码如下:

// RngTest.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <ctime>
#include <random>

using namespace std;

class MyClass
{
private:
    default_random_engine Rng;
public:
    MyClass(void)
        : Rng(time(NULL))
    {
    }
    ~MyClass(void)
    {
    }
    void Seed(unsigned int seed)
    {
        Rng.seed(seed);
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    MyClass rng;
    rng.Seed(100);
    return 0;
}

在 Visual Studio 2010(静态标准库,无 MFC/ATL,控制台项目)中,我看到以下编译错误:

c:\program files (x86)\microsoft visual studio 10.0\vc\include\random(1604): error C2064: term doesn't evaluate to a function take 0 arguments 1>
c:\users\vitaliy\documents\visual studio 2010 \projects\rngtest\rngtest\rngtest.cpp(25) :参见对函数模板实例化的参考 'void std::tr1::mersenne_twister<_Ty,_Wx,_Nx,_Mx,_Rx,_Px,_Ux,_Sx,_Bx,_Tx, _Cx,_Lx>::seed(_Gen &,bool)' 正在编译

这种编译失败的原因可能是什么?有没有办法在 Visual C++ 2010 中使用 default_random_engine 私有字段?

4

2 回答 2

2

我花了大约 4 个小时试图弄清楚这一点。万一其他人遇到这个...

default_random_generator只会采用 unsigned long 类型的种子。Int, unsigned int, long short byte dword 不会削减它。它必须是无符号整数。

另请注意,您不能以 0 为种子,否则会出现运行时错误。以下是我来之不易的编译代码...

unsigned long seed = pblock->GetInt(p_seed);
// We cannot seed with 0, so increment by 1 to avoid the error
seed++;
std::default_random_engine generator(seed);
于 2013-11-02T20:15:27.857 回答
0

有类似的问题。在 Visual C++10 中,您必须使用无符号类型作为种子!

于 2014-01-07T12:00:48.837 回答