Class data member

Source: Internet
Author: User

3.7.1 data member

Example 3-35

This example illustrates the syntax for declaring static members. The data member N of the task class is related to the task class and has nothing to do with any task object. Since N is static and static, it only has one class for the entire task, instead of having N for each task object. Figure 3-6 shows Class C, which has a non-static data member X and a static data member S.

We can use N to determine the number of existing Task objects. Therefore, we modify the constructor and destructor of the task class as follows:

Assuming that the static data member N is initialized to 0, N will save the number of task objects during running.

As shown in figure 3-35, static data members are declared within the class declaration, and static data members must also be defined.

Example 3-36

 

In this example, 3-35 is modified, and the definition of static data member N is added. As shown in the code above, static data members declared inside the class declaration must be defined outside of any program block. Note that the data member name is task: N rather than N. We initialize task: n to 0, but this is not necessary, because any variable defined outside of all program blocks will be automatically initialized to 0, unless the programmer provides a different initial value.

Static data members do not affect the sizeof of the class and its objects.

Example 3-37

In the system, the values of sizeof (C) and sizeof (C1) are both 16. If you modify the class declaration as follows:

The two sizeof expressions are still equal to 16 because static data members do not affect the sizeof of Class and Class objects.

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.