用static修饰类的成员函数,称为类的静态成员函数。
它属于类本身,而不是仅仅属于类的某个具体对象。
它没有this指针,所以不能访问非静态成员变量,只能访问类的静态成员变量和该类的其它静态成员函数。
但是类的普通非静态函数也可以调用类的静态函数。参见如下代码:
#include <iostream> class MyClass { private: int normalVar = 10; // 非静态成员 static int staticVar; // 静态成员 public: // 静态成员函数 static void staticFunc() { // normalVar = 20; // ❌ 编译报错!不能直接访问非静态变量 staticVar = 20; // ✅ 正确,可以访问静态变量 std::cout <<"staticFunc(): staticVar :" << staticVar << std::endl; // normalFunc(); // ❌ 编译报错!不能直接调用非静态函数 } void normalFunc() { // 普通函数可以随意调用静态函数(反过来是可以的) std::cout << "normalFunc(): call staticFunc() :" << std::endl; staticFunc(); // ✅ } }; // 静态成员变量必须在类外单独定义初始化 int MyClass::staticVar = 0; int main() { MyClass class1; class1.staticFunc(); class1.normalFunc(); return 0; }