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

前端 未结 6 615
执笔经年
执笔经年 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:13

    You can't access non-static data from a static function. This is because the static function can be called irrespective of whether there are any instantiated objects of the class. The non-static data, however, is dependent on a specific object (instantiation) of the class. Since you can't be sure that there are any objects instantiated when calling a static function, it is illogical (and therefore not allowed) to access non-static data from it.

    This question has been asked several times on SO in different forms / for different languages:

    • C#
    • Java
    • Python
    • PHP
    • Language-independent

提交回复
热议问题