我尝试创建一个具有default_random_engine 私有(private)字段的类。但是,这个类无法编译。我的简单控制台程序代码如下:
// 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 does not evaluate to a function taking 0 arguments 1>
c:\users\vitaliy\documents\visual studio 2010\projects\rngtest\rngtest\rngtest.cpp(25) : see reference to function template instantiation 'void std::tr1::mersenne_twister<_Ty,_Wx,_Nx,_Mx,_Rx,_Px,_Ux,_Sx,_Bx,_Tx,_Cx,_Lx>::seed(_Gen &,bool)' being compiled
编译失败可能是什么原因?有没有办法在 Visual C++ 2010 中使用 default_random_engine 私有(private)字段?
最佳答案
我花了大约 4 个小时试图解决这个问题。万一其他人遇到这个...
default_random_generator 将仅采用 unsigned long 类型的种子。 Int、unsigned int、长短字节双字不会削减它。它必须是无符号整数。
另请注意,您不能以 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);
关于c++ - 无法在 Visual C++ 2010 中使用 default_random_engine 字段创建类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17013242/