문제

I am beginner to C++ and have a doubt about static member variables and member functions.

I have implemented a class as follows -

class Foo
{
private:
    static int myVariable;
public:
    static void setMyVariable()
    {
        myVariable = 100;
    }

    static void resetMyVariable()
    {
        myVariable = 0;
    }
};

There are following considerations when I wrote a code like that -

  • I want only one instance of class Foo. Thats why I made all member variables and functions as static.
  • I don't want the outside code to touch myVariable

I have put this class in a header file and included in my main file. When I do this, I get an error undefined reference to Foo::myVariable

I want to know if I can write a code which can satisfy above requirements?

Thanks !

도움이 되었습니까?

해결책

You need to define static class variables somewhere: e.g. in your main C++ file,

int Foo::myVariable;

Note that technically, by making everything static, you may have no instances of Foo.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top