1

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);

};
Tibit
  • 73
  • 1
  • 5
  • "most vexing parse", look it up. – n. m. could be an AI Dec 02 '21 at 09:52
  • In a class definition, anything of the form `type name(parameters)` is interpreted as a member function declaration. – molbdnilo Dec 02 '21 at 09:55
  • `mt19937 generator(rd());` [Most vexing parse](https://stackoverflow.com/questions/7007817/a-confusing-detail-about-the-most-vexing-parse) – PaulMcKenzie Dec 02 '21 at 09:56
  • 2
    Contrary to popular belief, this is not the most vexing parse; `void f() { random_device rd; mt19937 generator(rd()); uniform_real_distribution unif(0.0, 1.0); }` would behave exactly as you were expecting. – molbdnilo Dec 02 '21 at 10:00

0 Answers0