#include <iostream> using namespace std; class Test { private: static int count; public: Test() { ++count; } ~Test() { --count; } // 静态成员函数 static int getCount() { return count; } }; int Test::count = 0; int main() { cout << "count = " << Test::getCount() << endl; Test t1; Test t2; cout << "count = " << t1.getCount() << endl; cout << "count = " << t2.getCount() << endl; Test *p = new Test(); cout << "count = " << p->getCount() << endl; delete p; cout << "count = " << Test::getCount() << endl; return 0; }
静态成员函数是类中的特殊成员函数:
1.静态成员函数没有隐藏的 this 参数
不能直接访问普通的成员函数和普通的成员变量
2.静态成员函数可以通过类名直接访问
访问方式:类名::静态成员函数名()
3.静态成员函数只能直接访问静态成员变量(函数)