私有静态类成员

时间:2014-07-11 22:05:42

标签: c++

当我们声明一个成员变量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;

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

4 个答案:

答案 0 :(得分:6)

是的,它确实意味着什么。请考虑以下示例,该示例会引发编译器错误,因为该成员是private。能够初始化私有变量与能够从任何上下文更改它不同。

class Something
{
  private:
    static int s_nValue;
};

int Something::s_nValue = 1;

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

答案 1 :(得分:2)

私有仍然意味着同样的事情:除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!
}

答案 2 :(得分:1)

  

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

我试着回答一个经典的例子。请考虑以下代码:

#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;
}

LIVE DEMO

在上面的示例中,我们使用私有static int来计算创建的foo个实例。我们制作了count static成员变量private,因为我们不希望除foo类型的对象之外的其他任何人混淆它。

这只是一个天真的例子,想想可能性。

答案 3 :(得分:0)

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

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

因此,即使应用于静态成员,private也有意义 - 它只是说其他类无法看到此成员。

相关问题