Reputation: 79
I have two classes: "Game" class and "Unit" class.
Game is instantiated just after the program starts in the Main function. Inside Game class constructor I created some "Unit" class instances.
Then I want one of my Units to run a method from the Game class instance I created in Main function (for example to use Game's built in random number engine)
Is that possible? What is the best way of accessing parent's instance method from the class instantiated within this class.
As I couldn't really get how to do it properly I decided to use "static" method, although my first needs was to use an instance of a Class. Still couldn't get it to work.. This is my tryout of use random from my Game class (but not an instance of that class as I wanted), I was able to only run a static print function but static random just throws an error: LNK2001 unresolved external symbol "public: static class std::random_device Game::rgen" (?rgen@Game@@2Vrandom_device@std@@A)
By the way mt19937 is giving similar error. Using Visual Studio 2015.
#include <iostream>
#include <random>
class Game;
class Unit;
class Game
{
public:
Game();
static void printSomething(); // test function
static std::random_device rgen; // main game random generator
// a shorthand function for quick generating random numbers
static int rnd(int min, int max){
std::uniform_int_distribution<int> uid(min, max);
return uid(rgen);
}
static double rnd(double min, double max){
std::uniform_real_distribution<double> urd(min, max);
return urd(rgen);
}
};
class Unit
{
public:
Unit() {
std::cout << "unit created\n";
Game::printSomething(); // this works
std::cout << "random num is " << Game::rnd(1,100) << "!\n"; // this doesn't work
}
};
// ********************************************** //
int main()
{
Game game; // main game instance
}
// ********************************************** //
Game::Game() {
Unit * unit = new Unit;
}
void Game:: printSomething() {
std::cout << "Printing something!\n";
}
Upvotes: 0
Views: 97
Reputation: 1767
You get that error since
static std::random_device rgen;
isn't declared outside class.
You should add the following line after the class definition:
std::random_device Game::rgen (*any constructor arguments needed*);
The reason that print works is, because it doesn't use the non-declared static variable rgen.
Upvotes: 2