私有静态类成员

Private static class members

本文关键字:成员 静态类      更新时间:2023-10-16

声明成员变量static时,它在类的所有实例之间共享。我听说应该考虑属于类本身的变量,而不是任何实例。这使我们可以初始化变量而不实例化类的任何对象,这是有意义的。

class Something
{
  public:
    static int s_nValue;
};
int Something::s_nValue = 1;
但是为什么允许初始化私有静态成员呢?
class Something
{
   private:
      static int s_nValue;
};
int Something::s_nValue = 1;

当我们谈论静态成员时,private甚至意味着什么吗?

是的,它确实意味着什么。考虑下面的例子,它抛出一个编译器错误,因为成员是private。能够初始化私有变量与能够从任何上下文中更改它是不一样的。

class Something
{
  private:
    static int s_nValue;
};
int Something::s_nValue = 1;
int main(){
    Something::s_nValue = 2; // Compiler error here.
}

Private仍然意味着同样的事情:您不能使用名称Something::s_nValue,除非在Something的成员(或友元,或Something中的嵌套类)的定义中。

int Something::s_nValue = 1;

Something成员的定义,即静态成员s_nValue

int Something::another_static_val = s_nValue;  // also okay
int OtherClass::x = Something::s_nValue;       // Illegal access!
int Something::getValue() const {
    return s_nValue;                // okay, getValue is a member of same class
}
int regularFunction() {
    return Something::s_nValue;     // Illegal access!
}

当我们谈论静态成员时,private甚至意味着什么吗?

我试着用一个经典的例子来回答。考虑下面这段代码:

#include <iostream>
class foo {
  static int count;
  int id;
public:
  foo() : id(++count) {}
  int getid() const { return id; }
};
int foo::count = 0;
int main() {
  foo f1, f2, f3;
  std::cout << f1.getid() << std::endl;
  std::cout << f2.getid() << std::endl;
  std::cout << f3.getid() << std::endl;
}

现场演示

在上面的示例中,我们使用私有static int来计算foo创建的实例。我们将countstatic成员变量命名为private,因为我们不希望除了foo类型的对象之外的任何人干扰它。

这只是一个简单的例子,想想各种可能性

Public、private和protected是类的属性,而不是对象的属性。它们的目的是让您指定的哪些部分对其他类可见,而不是对同一类的对象隐藏内容。所以,你可以这样写代码:

class A
{
public:
bool operator<(const A& other)
{
return this->val < other.val;
}
private:
int val;
};

所以,private即使应用于静态成员也是有意义的——它只是说其他类不能看到这个成员。