Pregunta

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 !

¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top