C++ static member functions and variables

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

    A static member function is one that can be called without an actual object of that kind. However, your function Environment::display uses the variables numOfRobots and robots, which both live in a particular instance of the Environment class. Either make display non-static (why do you want it to be static?) or make the robots static members of Environment too.

    In your case, I don't see a reason for making display or processKeySpecialUp static, so just make them normal member functions. If you wonder when a member function should be static, consider if that function would make sense if no objects of that class have been created (i.e. no constructors been called). If the function doesn't make sense in this context, then it shouldn't be static.

提交回复
热议问题