簡體   English   中英

在 class 中使用 std::mt19937 時出現編譯錯誤

[英]compilation error when std::mt19937 is used in a class

我試圖將main中的代碼封裝成一個class。main中的代碼運行良好。 當我將它移動到 class 時,我開始出現編譯錯誤。 錯誤是:error: 'rd' is not a type

#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';
}
 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);
    }
  };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM