c++ 在类中使用std::mt19937时出现编译错误

fquxozlt  于 2022-11-27  发布在  其他
关注(0)|答案(1)|浏览(265)

我尝试将main中的代码封装到一个类中。main中的代码运行良好。当我将其移动到一个类中时,开始出现编译错误。错误为:错误:'rd'不是型别

#include <random>
#include <iostream>
 class StdRandom
  {
     std::random_device rd;  //Will be used to obtain a seed for the random number engine
     std::mt19937 gen(rd()); //error
     std::uniform_int_distribution<> distrib; 
    
  public:
    StdRandom(int V)
    {
      std::uniform_int_distribution<> distribTmp(0, V);
      distrib = distribTmp;
    }
    int uniformInt()
    {
      return distrib(gen);
    }
  };

 
int main()
{
    std::random_device rd;  //Will be used to obtain a seed for the random number engine
    std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
    std::uniform_int_distribution<> distrib(1, 6);
 
    for (int n=0; n<10; ++n)
        //Use `distrib` to transform the random unsigned int generated by gen into an int in [1, 6]
        std::cout << distrib(gen) << ' ';
    std::cout << '\n';
}
z9gpfhce

z9gpfhce1#

class StdRandom
  {
     std::random_device rd;  //Will be used to obtain a seed for the random number engine
     std::mt19937 gen; //Standard mersenne_twister_engine seeded with rd()
     std::uniform_int_distribution<> distrib; 
    
  public:
    StdRandom(int V)
    {
      std::uniform_int_distribution<> distribTmp(0, V);
      distrib = distribTmp;
      std::mt19937 genTmp(rd());
      genTmp = gen;
    }
     int uniformInt()
    {
      return distrib(gen);
    }
  };

相关问题