C + + class scope and visible fields

Source: Internet
Author: User

data members and function members defined in a class are scoped to the entire class, which is visible only in the class (which contains the definition part of the class and the implementation part of the out-of-class function) and is invisible outside the class. If a "masking" phenomenon occurs, the members of the class have a small and scoped visible field, but at this point they can access the class member in the form of the this pointer or the " class Name::", which is similar to using "::" To access the global variable.

Example:

extern int x=100;

extern int z=100;

Class Example

{

int x;

int y;

Public:

Example (int x,int y)

{}

void print (int x)

{

cout<< "parameter overrides member x variable and Global x variable" <<x<<end1; parameter x covers global variables and local variables X

cout<< "member x variable" << (this->x) <<end1;

cout<< "member x variable" <<Example::x<<end1;

cout<< "Global x Variable" << (:: x) <<end1; Accessing Global variables X

cout<< "Global z variable" <<z<<end1; No formal parameter makes a mask on global variable z, and direct access to Z

}

}

int main ()

(

Example e;

X.print (5);

return 0;

)

Output Result:

5

0

0

100

200

C + + class scope and visible fields

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.