25. Static member variables of a class

Public member variables can be accessed by object name.

The member variables of each object are exclusive.

Member variables cannot be shared between objects and are generally set to private.

New requirement: count the number of objects of a class during program execution

                Ensure program security (can't use global variables)

                The current number of objects can be obtained at any time.

#include <stdio.h>

// int gcount=0; // global variables are unsafe

class Test
{
private:
    int mCount;
public:
    Test() : mCount(0)
    {
        mCount++;       //gcount++;
    }
    ~Test()
    {
        --mCount;          //gcount--;
    }
    int getCount()
    {
        return mCount;    //return gcount;
    }
};
Test gTest;
int main()
{
    Test t1;
    Test t2;
    printf("count = %d\n", gTest.getCount());
    printf("count = %d\n", t1.getCount());
    printf("count = %d\n", t2.getCount());
    return 0;

}

3 1s are printed because each object has a member variable.

Global variables are not safe. Static member variables can be defined in C++. Static member variables belong to the entire class. The lifetime of static member variables does not depend on any object. Public static member variables can be directly accessed through the class name. All objects share the class Static member variables, public static member variables can be accessed through the object name.

Characteristics of static member variables: directly modified by the static keyword when defining, static member variables need to be allocated space separately outside the class, and static member variables are located in the global data area inside the program.

    Type ClassName::VarName=value;

 #include <stdio.h>
class Test
{
private:
    static int cCount;
public:
    Test()
    {
        cCount++;
    }
    ~Test()
    {
        --cCount;
    }
    int getCount()
    {
        return cCount;
    }
};
int Test::cCount = 0;
Test gTest;
int main()
{
    Test t1;
    Test t2;
    printf("count = %d\n", gTest.getCount());
    printf("count = %d\n", t1.getCount());
    printf("count = %d\n", t2.getCount());
    Test* pt = new Test();
    printf("count = %d\n", pt->getCount());
    delete pt;
    printf("count = %d\n", gTest.getCount());
    return 0;

}

A class can define static member variables through the static keyword, which belong to the class. The global data area allocates space, and each object can access the static member variables. The lifetime is the program running period.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325884402&siteId=291194637