C++ static member functions and variables

前端 未结 6 423
北恋
北恋 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:29

    There are 2 issues here - the algorithm you're trying to implement and the mechanics of why it won't compile.

    Why it doesn't compile.

    You're mixing static and instance variables/methods - which is fine. But you can't refer to an instance variable from within a static method. That's the "invalid use" error. If you think about it, it makes sense. There is only one "static void display()" method. So if it tries to refer to the non-static (instance) variable "robots", which one is it referring to? There could be 10 ... or none.

    The logic you are trying to implement.

    It looks like you want a single Environment class that manages N robots. That's perfectly logical. One common approach is to make Environment a 'singleton' - an instance variable that only allows for a single instance. Then it could allocate as many robots as it want and refer to them freely because there are no static variables/methods.

    Another approach is to just go ahead and make the entire Environment class static. Then keep a (static) list of robots. But I think most people these days would say option #1 is the way to go.

提交回复
热议问题