Why can I only access static members from a static function?

前端 未结 6 634
执笔经年
执笔经年 2020-12-10 03:48

I have a static function in a class.

whenever I try to use non static data member, I get following compile error.

An object reference is required for the non

6条回答
  •  半阙折子戏
    2020-12-10 04:17

    A static method cannot directly access any non-static member variables of a class.

    After all : a static method can be called without an instance of the class even being in existance. How do you want to access a member variable on a non-existing instance??

    (of course, as Mehrdad pointed out: you could pass an instance of your class to a static method and access everything on that instance - but that's not what you're talking about, right?)

提交回复
热议问题