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.