26. Static member functions of classes

If the object is not defined, the object cannot be used. If the static member variable is mobilized through the class name, the program is not safe.

If we need:

    Static member variables can be accessed without relying on the object.    

    The safety of static member variables must be guaranteed.

    It is convenient and quick to obtain the value of static member variables.

Static member functions can be defined in C++:

    A static member function is a special member function in a class, which belongs to the entire class. It can directly access the public static member function through the class name, and can access the public static member function through the object name. Directly modify member functions with the static keyword: static void func1() {}

#include <stdio.h>
class Demo
{
private:
    int i;
public:
    int getI();
    static void StaticFunc(const char* s);
    static void StaticSetI(Demo& d, int v);
};
int Demo::getI ()
{
    return i;
}
void Demo::StaticFunc(const char* s)
{
    printf("StaticFunc: %s\n", s);
}
void Demo::StaticSetI(Demo& d, int v)
{
    di = v ; // Change to i=v; static member functions cannot directly access member variables
}
int main()
{
    Demo::StaticFunc("main Begin...");   
    Demo d;
    Demo::StaticSetI(d, 10);    
    printf("d.i = %d\n", d.getI());
    Demo::StaticFunc("main End...");
    return 0;

}

Static member functions cannot directly access member variables.

Static member functions: 1. Static member functions do not have this pointer, 2. Static member functions cannot access ordinary member variables (functions) --- Note (because there is no this pointer)

Ordinary member function: 1. It cannot be called directly through the class name, and must depend on the specific object.

The same points: 1. All objects share 2. Access static member variables (functions) 3. Directly call through the object name.

#include <stdio.h>
class Test
{
private:
    static int cCount;
public:
    Test()
    {
        cCount++;
    }
    ~Test()
    {
        --cCount;
    }
    static int GetCount()
    {
        return cCount;
    }
};
int Test::cCount = 0;
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;
}

Guess you like

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