私有静态类成员
Private static class members
声明成员变量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
创建的实例。我们将count
的static
成员变量命名为private
,因为我们不希望除了foo
类型的对象之外的任何人干扰它。
这只是一个简单的例子,想想各种可能性
Public、private和protected是类的属性,而不是对象的属性。它们的目的是让您指定类的哪些部分对其他类可见,而不是对同一类的对象隐藏内容。所以,你可以这样写代码:
class A
{
public:
bool operator<(const A& other)
{
return this->val < other.val;
}
private:
int val;
};
所以,private即使应用于静态成员也是有意义的——它只是说其他类不能看到这个成员。
相关文章:
- 使用静态成员声明类时遇到问题
- (为什么)我们可以在初始化中将非静态类成员分配给静态变量吗?
- 从相同类型的静态成员进行类内初始化
- 是否通过单元化指针UB访问静态类成员
- 初始化与类类型相同的静态成员(静态初始化顺序问题)
- 从静态成员函数访问私有非静态类变量 - C++
- 在子类中填充静态类成员
- 作为成员的静态类模板实例会导致未解析的外部符号错误
- uninit_member:非静态类成员字段 m_cJobState.bstatus 未在此构造函数中初始化,也不在其调
- uninit_member:非静态类成员m_wszParams未在此构造函数中初始化,也不在它C++中调用的任何函数中初
- 说明通过指针访问非静态类成员函数
- 静态类数据成员的线程安全
- 具有静态成员的类的前向声明
- 枚举不是非静态数据成员或类的基类
- 静态类成员的使用
- 静态类成员不是与 this 指针没有关联吗?
- 使用静态类成员而不是私有字段之间的速度差异是什么?
- 如何在 Visual Studio 中显示模板的静态类成员
- 即使没有析构函数,非静态类成员也会被销毁吗?
- 静态模板函数访问静态类成员