Reputation: 141
NOTE: coord is a std::pair
class Random
{
public:
Random()
{
gen.seed(rd());
};
coord rnd_coord(int x, int y)
{
std::uniform_int_distribution<> dist_x(0, x - 1);
std::uniform_int_distribution<> dist_y(0, y - 1);
coord temp;
temp.first = dist_x(gen);
temp.second = dist_y(gen);
return temp;
}
private:
static std::random_device rd;
static std::mt19937 gen;
};
Then in main.cpp
int x;
Random R;
coord C;
C = R.rnd_coord(10, 10);
std::cout << C.first << ", " << C.second << std::endl;
std::cin >> x;
return 0;
Im doing some tests with but I'm having a lot of issues with it :(, tbh I havent programmed in a while. Anyway, I want to make a helper function that will return random coordinates in the specified bounds, said function is in "snake_utility.h", but as it was giving me errors i put it in a class, and now I get linker errors:
Error 1 error LNK2001: unresolved external symbol "private: static class std::random_device Random::rd" (?rd@Random@@0Vrandom_device@std@@A) C:\Users\Reethok\Desktop\C++\Pet Projects\Snake\Snake\main.obj Snake Error 2 error LNK2001: unresolved external symbol "private: static class std::mersenne_twister_engine Random::gen" (?gen@Random@@0V?$mersenne_twister_engine@I$0CA@$0CHA@$0BIN@$0BP@$0JJAILANP@$0L@$0PPPPPPPP@$06$0JNCMFGIA@$0P@$0OPMGAAAA@$0BC@$0GMAHIJGF@@std@@A) C:\Users\Reethok\Desktop\C++\Pet Projects\Snake\Snake\main.obj Snake Error 3 error LNK1120: 2 unresolved externals C:\Users\Reethok\Desktop\C++\Pet Projects\Snake\Debug\Snake.exe 1 1 Snake
Thanks in advance!
Upvotes: 1
Views: 1611
Reputation: 206607
Non-static
member variables of a class are constructed when you construct an instance of the class. The static
member variables, on the other hand, are same for all instances of the class. They need to be defined explicitly.
You need to define the static
member variables in the enclosing namespace. Add
std::random_device Random::rd;
std::mt19937 Random::gen;
in a .cpp file.
Upvotes: 6