简体   繁体   English

为什么我们不允许在没有公共成员函数的情况下访问类外的私有静态成员?

[英]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.

相关问题 私有/公共静态成员函数 - Private/public static member function 为什么此公共成员函数不能在类内部声明的私有struct成员上调用decltype? - Why can't this public member function call decltype on a private struct member declared inside the class? 为什么这个朋友的功能无法访问该类的私有成员? - Why this friend function can't access a private member of the class? Class 成员 function 在公共、受保护和私有之外声明 - Class member function declared outside of public, protected and private 为什么在类声明之外不允许使用virtual和static关键字? - Why virtual & static keywords aren't allowed outside class declaration? 在类定义之外定义私有成员函数并使用静态数据 - defining a private member function outside class definition and use of static data 如何在另一个类的静态成员函数中访问私有静态变量? - How to access private static variable in static member function of another class? 私有静态成员不能从公共静态成员函数访问吗? - Private static member not accessilble from public static member function? C ++:从类外部访问公共成员函数 - C++: Access to a public member function from outside of a class C ++:公共静态成员函数如何访问私有实例成员变量? - C++: How can a public static member function access private instance member variables?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM