Problem in C++ class with static variables and fun

2019-07-31 08:44发布

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

2条回答
Lonely孤独者°
2楼-- · 2019-07-31 09:02

You have only declared the static members. You should also define them in a cpp file like this

int FibonacciGenerator::num1 /*= 0*/;
int FibonacciGenerator::num2 /*= 1*/;
int FibonacciGenerator::counting /*= 0*/;

when you write

static T v; //if static were removed, this would also be a definition

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

查看更多
欢心
3楼-- · 2019-07-31 09:05

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:

//Begin FibonacciGenerator.hpp
#ifndef FIBONACCI_GENERATOR_HPP
#define FIBONACCI_GENERATOR_HPP
class FibonacciGenerator
{
private:
    static int num1, num2, counting;

public:
/* as above */
};
#endif //FIBONACCI_GENERATOR_HPP
//End FibonacciGenerator.hpp

//Begin FibonacciGenerator.cpp
#include "FibonacciGenerator.h"
int FibonacciGenerator::num1;
int FibonacciGenerator::num2;
int FibonacciGenerator::counting;
//End FibonacciGenerator.cpp

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.

查看更多
登录 后发表回答