静态成员变量在类中仅仅是声明,没有定义,所以要在类的外面定义,实际上是给静态成员变量分配内存。通过类名,对象,成员函数都可以访问静态成员变量。
类的静态成员变量需要在类外分配内存空间。
静态成员函数只能调用静态成员变量。
成员函数可以调用静态成员变量和静态成员函数。
类内局部静态变量所有对象共享一个,在编译时分配内存,在第一次函数跑到这里时初始化,之后不再初始化。
#include <iostream>
#include <string>
using namespace std;
class test
{
public:
static int m_value1; //声明私有类的静态成员变量
int m_value2;
public:
test()
{
m_value1++;
}
static int getValue1(){
return m_value1;
}
int getValue2(){
static int i = 1;//编译时赋值,所有对象公用一个
return ++i;
}
int getValue() //定义类的静态成员函数
{
return m_value1;
}
};
int test::m_value1 = 0; //类的静态成员变量需要在类外定义并且分配内存空间
int main()
{
test t1;
test t2;
test t3;
cout << "test::m_value1 = " << test::m_value1 << endl; //通过类名直接调用公有静态成员变量,获取对象个数
cout << "t3.m_value1 = " << t3.m_value1 << endl; //通过对象名名直接调用公有静态成员变量,获取对象个数
cout << "t3.getValue() = " << t3.getValue() << endl; //通过对象名调用普通函数获取对象个数
cout << "t1.getValue2() = " << t1.getValue2() << endl;//2
cout << "t2.getValue2() = " << t1.getValue2() << endl;//3
cout << "t3.getValue2() = " << t1.getValue2() << endl;//4
return 0;
}`在这里插入代码片`