Can someone tell me what is problem in the following class, g++ is giving errors on ubuntu:
class FibonacciGenerator { private: static int num1, num2, counting; public: static void Reset() { num1 = 0; num2 = 1; counting = 1; } static int GetCount() { return counting; } static int GetNext() { int val = 0; if(counting == 1) val = num1; else if(counting == 2) val = num2; else { val = num1 + num2; num1 = num2; num2 = val; } counting ++; return val; } };
You have only declared the static members. You should also define them in a cpp file like this
when you write
inside a class, it is only a declaration, but every program must contain exactly one definition of every variable that is used (as per the One-Definition-Rule). hth
The statement
static int num1, num2, counting;
in a class definition does not define those variables, it only declares them. If they are used they must also be defined.A complete example of this is as follows:
If FibonacciGenerator is declared in a namespace, then these static member definitions must also be in that namespace.
Using static members like this is probably a very bad idea. It would be better to make them instance variables, so that you could have multiple independent
FibonacciGenerators
in separate parts of the code.