在C语言中,我们知道有static静态变量,生命周期与作用域都跟普通变量有所不同。而在C++的类中,也有静态成员变量同时还有静态成员函数,先来看看C++中静态成员变量与静态成员函数的语法:
#include
#include
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"); }
针对静态成员变量的以上几点,我们把上边的代码修改如下,用于统计当前对象的个数:
#include
#include
using namespace std; class test { private: static int m_value1; //定义私有类的静态成员变量 public: static int m_value2; //定义私有类的静态成员变量 public: test() { m_value1++; m_value2++; } int getValue() //定义类的静态成员函数 { return m_value1; } }; int test::m_value1 = 0; //类的静态成员变量需要在类外分配内存空间 int test::m_value2 = 0; //类的静态成员变量需要在类外分配内存空间 int main() { test t1; test t2; test t3; cout << "test::m_value2 = " << test::m_value2 << endl; //通过类名直接调用公有静态成员变量,获取对象个数 cout << "t3.m_value2 = " << t3.m_value2 << endl; //通过对象名名直接调用公有静态成员变量,获取对象个数 cout << "t3.getValue() = " << t3.getValue() << endl; //通过对象名调用普通函数获取对象个数 system("pause"); }
编译输出:
从输出,貌似得到我们想要的效果,但是C++中讲究的是封装性,以上代码,有2个不妥之处
1、类名或对象名能直接访问成员变量,也就是说成员变量能直接被外界修改
2、我们使用了一个成员函数来获取当前的对象个数,看似没问题,但是必须要定义对象,通过对象去调用,但有时候我们不想定义对象,也能使用类中的成员函数,这就是我们要说的类的静态成员函数。
#include
#include
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"); }
这样我们就直接能通过类名去访问静态成员函数,获取对象个数,不通过任何对象。
静态成员函数在C++中的作用很强大,包括后边的介绍的单例模式、二阶构造模式,都用到静态成员函数及静态成员变量。
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/202704.html原文链接:https://javaforall.net
