1
下面的代碼生成的所有對象對於randomNumber1和randomNumber2具有相同的值。如何正確使用std :: default_random_engine?如何用隨機數據成員值創建對象? C++
#include <random>
#include <iostream>
class Food{
public:
int randomNumber1;
int randomNumber2;
Food(){
std::default_random_engine generator;
std::uniform_int_distribution<int> distribution(1,40);
std::uniform_int_distribution<int> distribution2(1,30);
randomNumber1 = distribution(generator) * 20;
randomNumber2 = distribution2(generator) * 20;
};
};
int main(){
Food * food = new Food();
std::cout << food->randomNumber1 << " " << food->randomNumber2 << std::endl;
Food * food1 = new Food();
std::cout << food1->randomNumber1 << " " << food1->randomNumber2 << std::endl;
Food * food2 = new Food();
std::cout << food2->randomNumber1 << " " << food2->randomNumber2 << std::endl;
return 0;
};
或者更好的是,將它作爲一個構造函數參數。 'static' ...這取決於調用者決定:) – xtofl
或者使用'std :: random_device'來獲得一個真正的隨機種子。 – Unimportant
@不重要是的,補充說。 –