在C++的类中,有静态成员变量和静态成员函数
#include <iostream>
#include <string>
 
using namespace std;
 
class test
{
private:
    static int m_value;		//定义类的静态成员变量
 
public:
 
    static int getValue()	//定义类的静态成员函数
    {
    	return m_value;
    }
};
 
int test::m_value = 12;		//类的静态成员变量需要在类外分配内存空间
 
int main()
{
    test t;
 
    cout << t.getValue() << endl;
    system("pause");
}
 
在上面的代码中,在test类中分别有一个静态成员变量和静态成员函数
- 静态成员变量归整个类所有
 - 静态成员变量的生命不依赖于任何对象,为程序的生命周期
 - 可以通过类名直接访问共有静态成员变量
 - 所有对象共享类的静态成员变量
 - 可以对象名访问共有静态成员变量
 - 静态成员变量需要在类外单独分配空间
 - 静态成员变量在程序内部位于全局数据区
 
根据静态成员变量的特点,我们可以有下列的代码
#include <iostream>
#include <string>
 
using namespace std;
 
class test
{
private:
    static int m_value;		//定义私有类的静态成员变量
 
public:
    test()
    {
    	m_value++;
    }
 
    static int getValue()		//定义类的静态成员函数
    {
    	return m_value;
    }
};
 
int test::m_value = 0;		//类的静态成员变量需要在类外分配内存空间
 
int main()
{
    test t1;
    test t2;
    test t3;
 
    cout << "test::m_value2 = " << test::getValue() << endl;	//通过类名直接调用公有静态成员函数,获取对象个数
    cout << "t3.getValue() = " << t3.getValue() << endl;		//通过对象名调用静态成员函数获取对象个数
    system("pause");
}
 
上面的代码中,我们可以直接通过类名去访问静态成员函数,获取对象个数
静态成员函数
- 静态成员函数的类的一个特殊成员函数
 - 静态成员函数归整个类所有,没有this指针
 - 静态成员函数只能直接访问静态成员变量和静态成员函数
 - 可以通过类名直接访问类的共有静态成员函数
 - 可以通过对象名访问类的共有静态成员函数
 - 定义静态成员函数,直接使用static关键字修饰即可
 





![[附源码]计算机毕业设计基于Springboot物品捎带系统](https://img-blog.csdnimg.cn/a192c9500a184a6ba2d028d985ce44f5.png)














