Why cannot I call non-static members (attributes) in the static method (function) of a class )?

Source: Internet
Author: User

This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/ZOLoveGD/archive/2008/09/14/2914559.aspx
The program will eventually be executed in the memory, and variables can be accessed only when they have a place in the memory.

Static members of a class (variables and methods) belong to the class itself. When the class is loaded, the memory is allocated and can be directly accessed through the class name. Non-static members (variables and methods) it is a class object, so the memory is allocated only when the class object is generated (the instance of the class is created) and then accessed through the Class Object (instance.

An error occurs when a static member of a class accesses its non-static member because the static member of the class already exists when the non-static member of the class does not exist, an error occurs when accessing something that does not exist in the memory:

Class ca {
PRIVATE:
Int A; // non-static member. Memory is allocated when a class instance is created. different instances of the class correspond to different memory regions.
Static int B; // static member. Memory is allocated when the class is loaded. all instances of the class are shared.

Public:
Void FA (void ){
A = 1;
B = 1;
}

Static void FB (void ){
// A = 1; // non-static member can't be accessed by static function
B = 1;
}
};
/**
* Static member must be initialized before using ,.
* Or error: unresolved external symbol "Private: static int CA: B"
*/
Int CA: B = 1;

Int main (void ){

CA;
CA. FA ();

CA: FB ();

Return 0;
}

This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/ZOLoveGD/archive/2008/09/14/2914559.aspx

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.