Static member variables in C ++ classes and static member functions

1. C ++ static member variables

First look ordinary member variables

  • By object name can access the public member variables
  • Ordinary member variables of each object is unique, can not be shared between objects

In C ++, you can also define a static member variables

  • Static member variables belongs to the class of all, static member variables for all objects share classes
  • Static member variables of the life cycle does not depend on any object
  • By class name and the object name to access public static member variables

The definition of static member variables

  • Static member variables declared inside the class , when you declare directly through the static keyword modification
  • Static member variables defined outside of the class initialization , grammar rulesType ClassName::VarName = value;
  • Static member variables do not take the size of the class , but separately allocated space outside the class (global data)
#include <stdio.h>

class Test
{
private:
    static int c;
};

int Test::c = 0;

2. static member function

Unlike a static member variables is similar to the static member function is a class of special member functions

  • Static member function belongs to the class of all
  • By class name and the object name to access public static member function
  • Static member functions can only access static member variables and static member functions
class Demo
{
public:
    static void StaticFunc(const char *s)
    {
        printf("StaticFunc: %s\n", s);
    }

    static void StaticSetI(Demo &d, int v);
};

void Demo::StaticSetI(Demo &d, int v)
{
    d.i = v;
}

Static member function VS ordinary member functions

3. combat exercises

The following requirements

  • During the program runs statistical number of objects of a class
  • You can not use global variables
  • Any time you can get the current number of objects
#include <stdio.h>

class Test
{
private:
    static int cCount;
public:
    Test();
    ~Test();
    static int GetCount();
};

int Test::cCount = 0;

Test::Test()
{
    cCount++;
}

Test::~Test()
{
    --cCount;
}

int Test::GetCount()
{
    return cCount;
}

int main()
{
    printf("count = %d\n", Test::GetCount());

    Test t1;
    Test t2;

    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", Test::GetCount());

    return 0;
}

Static member variables in C ++ classes and static member functions

Guess you like

Origin www.linuxidc.com/Linux/2019-09/160747.htm