私有静态变量

Jig*_*asa 0 c++ static class

为什么我们必须声明静态成员函数来访问私有静态变量?为什么不简单地使用公共函数来访问s_nValue?我的意思是为什么使用静态成员函数而不是非静态公共函数更好?

class Something
{
  private:
  static int s_nValue;

};

int Something::s_nValue = 1; // initializer


int main()
{

}
Run Code Online (Sandbox Code Playgroud)

Bor*_*der 5

为什么我们必须声明静态成员函数来访问私有静态变量?

你不必:

class Something
{
  private:
  static int s_nValue;

  public:
  static int staticAccess() { return s_nValue; }
  int Access() { return s_nValue; }

};

int Something::s_nValue = 1; // initializer


int main()
{
    Something s;
    Something::staticAccess();
    s.Access();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这两种方法都可以在这里看到

话虽这么说,使用非静态成员函数来访问静态变量并没有多大意义(因为你需要一个类的实例才能调用它).