I'm a newer of C++. I want to use random object in my class, here is my code:
#include <random>
class de {
private:
// random object
random_device rd;
mt19937 generator(rd());
uniform_real_distribution<double> unif(0.0, 1.0);
};
But here comes some error message. (I delete some unimportant part of code so the number of line aren't correct.)
In file included from test.cpp:4:0:
de.hpp:26:23: error: 'rd' is not a type
mt19937 generator(rd());
^~
de.hpp:27:44: error: expected identifier before numeric constant
uniform_real_distribution<double> unif(0.0, 1.0);
^~~
de.hpp:27:44: error: expected ',' or '...' before numeric constant
de.hpp: In member function 'double de::run()':
de.hpp:47:42: error: no matching function for call to 'de::unif(<unresolved overloaded function type>)'
int x1 = this->unif(generator);
^
de.hpp:27:39: note: candidate: std::uniform_real_distribution<double> de::unif(int)
uniform_real_distribution<double> unif(0.0, 1.0);
^~~~
de.hpp:27:39: note: no known conversion for argument 1 from '<unresolved overloaded function type>' to 'int'
test.cpp: In function 'int main()':
test.cpp:8:5: error: redefinition of 'int main()'
int main() {
^~~~
In file included from test.cpp:4:0:
de.hpp:58:5: note: 'int main()' previously defined here
int main() { return 0; }
^~~~
After I use {}
to replace ()
, the error disappeared.
#include <random>
class de {
private:
// random object
random_device rd;
mt19937 generator{rd()};
uniform_real_distribution<double> unif{0.0, 1.0};
};
I want to know what the main difference between these two parantheses? I also know another way can work:
#include <random>
class de {
private:
// random object
random_device rd;
mt19937 generator = mt19937(rd());
uniform_real_distribution<double> unif = uniform_real_distribution<double>(0.0, 1.0);
};