Static member understanding

Source: Internet
Author: User

 

Sometimes some data in the program needs to be permanently saved or called globally for other reasons, but the global data is dangerous for development. Static is introduced here, which is very useful.

 

I understand static as follows:

 

When an object is generated by a common member in a class, each member is associated with an object. Therefore, an object can call its own members, so this pointer makes sense. For static declared members, this pointer is only associated with the class. this member is not instantiated when an object is generated, therefore, the object cannot be called for this member, and the this pointer is meaningless.

 

In addition, static is advantageous, can replace some global functions, and has encapsulation attributes. The Code is as follows:

 

Test. h

 

 

# Ifndef TEST_H

# Define TEST_H

 

# Include <iostream>

Using namespace std;

 

Class Test

{

Public:

Test ();

Void set ();

Void print ();

Virtual ~ Test ();

Protected:

Private:

Static int num; // Private static member with Encapsulation

// Static int num = 0; // cannot be defined during declaration. But const static int num = 0; can be defined,.

};

# Endif // TEST_H

 

# Include "../include/Test. h"

Int Test: num = 0; // static member Initialization

Test: Test ()

{

// Ctor

// This-> num = 0; // The static member can be defined only once and cannot be defined in class initialization.

}

Void Test: set ()

{

Num ++;

}

Void Test: print ()

{

Cout <num <endl;

}

 

Test ::~ Test ()

{

// Dtor

}

 

# Include <iostream>

# Include "./include/Test. h"

Using namespace std;

 

Int main ()

{

Test t;

// T. num = 9; // Private Members cannot use

T. set ();

T. print ();

Return 0;

}

 

 

Hope the majority of users will give guidance...

 

From the column Leeboy_Wang

Related Article

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.