C ++ - like static member variables

I. Review of member variables

1. be able to access public member variables by object name
2. The member variables of each object is unique
3. member variables can not be shared between objects
Q: new demands
1. statistical number of a class of objects during program run
2. the security assurance program (can not use global variables)
3. the number of the current object may be readily available
code sample

#include <iostream>
using namespace std;

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

Test gTest;

int main()
{
    Test t1;
    Test t2;

    cout<<"gTest.getCount()="<<gTest.getCount()<<endl;
    cout<<"t1.getCount()="<<t1.getCount()<<endl;
    cout<<"t2.getCount()="<<t2.getCount()<<endl;

    return 0;
}

The results shown in FIG operation
C ++ - like static member variables
occurs because the result is mCount defined separately generated at each single object construction, the number of the output is also Count 1

II. Static member variables

A. You can define a static member variables in C ++
1. static member variables that belong to all classes throughout the
life cycle 2. static member variables does not depend on any object
3. public static member variables can be accessed directly through the class name
4. All objects share classes static member variables
5. public static member variable can be accessed through the object name
B. characteristics static member variable of
1. in the definition directly modified by the static keyword
2. the static member variables outside the class requires a separate distribution space
3. static member variable located within the program global data
syntax rules: the Type ClassName: VarName = value
code sample

#include <iostream>
using namespace std;

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

int Test::mCount=0;

Test gTest;

int main()
{
    Test t1;
    Test t2;

    cout<<"gTest.getCount()="<<gTest.getCount()<<endl;
    cout<<"t1.getCount()="<<t1.getCount()<<endl;
    cout<<"t2.getCount()="<<t2.getCount()<<endl;

    return 0;
}

The results shown in FIG run
C ++ - like static member variables
summary:
1. The static class can define static member variable key
2. All static member variables belonging to the class
3. Each object can access a static member variable
4. static member variables in the global data area allocated space
lifetime 5. static member variables for the program run

Guess you like

Origin blog.51cto.com/13475106/2406508