C++ static member functions and variables

前端 未结 6 519
北恋
北恋 2021-01-31 11:40

I am learning C++ by making a small robot simulation and I\'m having trouble with static member functions inside classes.

I have my Environment class defined like this:<

6条回答
  •  你的背包
    2021-01-31 12:20

    The first error says that you cannot use non-static members in static member functions.

    The second one says that you need to define static members in addition to declaring them You must define static member variables outside of a class, in a source file (not in the header) like this:

    int Environment::numOfRobots = 0;
    

    You don't need any static members. To have an absolutely correct and portable GLUT interface, have a file-level object of type Environment and a file-level (non-member) function declared with C linkage. For convenience, have also a member function named display.

    class Environment 
    {
     public:
       void display() { ... }
       ... 
    };
    
    static Environment env;
    extern "C" void display () { env.display(); }
    

提交回复
热议问题