[英]Why aren't we allowed to access a private static member outside class without public member function?
This may be a silly doubt but I am not able to understand that why I am not able to access a private static data member outside the class when I am allowed to define it.这可能是一个愚蠢的疑问,但我无法理解为什么当我被允许定义它时我无法访问类外的私有静态数据成员。
For ex: in the following code:例如:在以下代码中:
class foo
{
static int A;
public:
int getA{return A;}
};
//This is allowed
int foo:A=0;
int main()
{
//This gives error
cout<<foo:A;
}
int foo::A = 0;
allocates storage for the member variable A
, and initializes it with 0
(actually a static is by default initialized with 0
, so the assignment is superfluous).为成员变量
A
分配存储空间,并用0
初始化它(实际上静态默认用0
初始化,因此赋值是多余的)。 You do this only once in the implementation .cpp file.您只在实现 .cpp 文件中执行此操作一次。 Then everyone will be able to instantiate your class without any linker issues.
然后每个人都可以在没有任何链接器问题的情况下实例化您的类。 Note that you cannot do this again, ie assigning later
foo::A = 42;
请注意,您不能再次执行此操作,即稍后分配
foo::A = 42;
will not compile, so you don't break any access rules.不会编译,因此您不会违反任何访问规则。 The fact that you must explicitly allocate storage is a language rule, which in my opinion creates more confusion (I'd make the compiler automatically allocate the storage when you declare the static).
您必须显式分配存储这一事实是一种语言规则,在我看来,这会造成更多混乱(当您声明静态时,我会让编译器自动分配存储)。
So, to conclude, being allowed to define a private member is by far not as dangerous as being able to later access it/modify it, and is very different from the latter.因此,总而言之,允许定义私有成员远没有能够在以后访问/修改它那么危险,并且与后者有很大不同。 The object is already sealed for the outside world once the member has its storage allocated.
一旦成员分配了其存储空间,该对象就已经为外部世界密封了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.