The first class of 25 class static member variables

Recalling the member variables
through to access the public member variables object name
of each object member variables are exclusive
member variables can not be shared (member variables are generally set to private) between objects

New demand
statistics during the program run the number of objects of a class of
assurance procedures security (can not use global variables)
number can always get the current object

Try Solution

#include <stdio.h>

class Test
{
private:
    int mCount;
public:
    Test() : mCount(0)
    {
        mCount++;
    }
    ~Test()
    {
        --mCount;
    }
    int getCount()
    {
        return mCount;
    }
};

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;
}

This approach is clearly above failure.

Function can be met by a global variable, but does not meet the security requirements of the user. In order to achieve customer demand, we will debut a static variable.

Can be defined in C ++ static member variables
- static member variables belongs to the class of all
- the life cycle of a static member variables does not depend on any object
- be a public static member variables accessed directly through the class name
- static objects all share classes member variables
- can access the public static member variables by object name

Static characteristics of the member variables
- when defining directly by modifying the static keyword
- static member variables need to allocate a separate space outside the class
- a static member variable is located in the internal procedures and global data

Grammar rules
Type ClassName :: VarName = value

If the class, so that a static variable is defined:

private:
    static int mCount;

会出现编译错误,提示在链接的时候找不到mCount这个变量所对应的存储空间。

既然是静态成员变量,那么这个变量就不隶属于任何的对象了。因此需要单独定义它,使得编译器知道这个静态成员变量需要在全局数据区分配存储空间。

#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;
}

小结:
类中可以通过static关键字定义静态成员变量
静态成员变量隶属于类所有
每一个对象都可以访问静态成员变量
静态成员变量在全局数据区分配空间
静态成员变量的生命周期为程序运行期

 

Guess you like

Origin www.cnblogs.com/-glb/p/11874136.html