C++第26课--类的静态成员函数

本文学习自 狄泰软件学院 唐佐林老师的 C++课程


通过需求:《随时可以获取当前对象的数目》来引出 类的静态成员函数;
方案1: 当前对象数目为私有的静态只读变量,可以通过成员函数获取,但是必须要定义新的对象才能获取到,舍弃。

方案2:将当前对象数目设置为public 的静态成员变量,通过类名访问,但是非常不安全,可以随意修改,舍弃。

方案3:将当前对象数目设置为private 的静态成员变量,通过公有静态成员函数访问 private静态成员变量,再通过类名或对象名访问公有静态成员函数。可行。


实验1:静态成员函数使用:公有静态成员函数可以通过类名和对象名直接访问

通过对象名直接访问 公有静态成员函数
通过类名直接访问 公有静态成员函数

实验2:通过公有静态成员函数 随时可以获取当前对象的数目

通过类名访问公有静态成员函数
通过对象名访问共有静态成员函数
通过指针访问共有静态成员函数

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

实验1:静态成员函数使用:公有静态成员函数可以通过类名和对象名直接访问

通过对象名直接访问 公有静态成员函数
通过类名直接访问 公有静态成员函数

#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)
{
    d.i = v;
}

int main()
{
    Demo::StaticFunc("main Begin...");
    
    Demo d;

	d.StaticSetI(d, 10);//通过对象名直接访问 静态成员函数
    
    Demo::StaticSetI(d, 10);//通过类名直接访问 静态成员函数
    
    printf("d.i = %d\n", d.getI());
    
    Demo::StaticFunc("main End...");
    
    return 0;
}


mhr@ubuntu:~/work/c++$ 
mhr@ubuntu:~/work/c++$ g++ 26-2.cpp
mhr@ubuntu:~/work/c++$ ./a.out 
StaticFunc: main Begin...
d.i = 10
StaticFunc: main End...
mhr@ubuntu:~/work/c++$ 

在这里插入图片描述

实验2:通过静态成员函数 随时可以获取当前对象的数目
通过类名访问公有静态成员函数
通过对象名访问共有静态成员函数
通过指针访问共有静态成员函数

#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;
}
发布了207 篇原创文章 · 获赞 100 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/LinuxArmbiggod/article/details/104108501
今日推荐