简体   繁体   English

为什么所有对象的类的静态成员都相同?

[英]Why are the static members of a class the same for all objects?

为什么我们不为不同的对象提供不同的静态变量副本?

Because they would be instance members then. 因为他们将成为实例成员

The primary characteristic of static members is that they're shared by all the instances of the class. 静态成员的主要特征是它们由类的所有实例共享。

Because the section $9.4.2/1 from the C++ Standard (2003) says, 因为C ++标准(2003)中的$ 9.4.2 / 1部分说,

A static data member is not part of the subobjects of a class. 静态数据成员不是类的子对象的一部分。 There is only one copy of a static data member shared by all the objects of the class. 该类的所有对象共享的静态数据成员只有一个副本。

Since the Standard alone decides what C++ is, what not, so it's how C++ has been designed! 既然标准单独决定了什么是C ++,那么C ++就是如何设计的!

Static members are more like global objects. 静态成员更像是全局对象。 The same copy belong to all objects! 同一副本属于所有对象!

See this post for detail answer : Do static members of a class occupy memory if no object of that class is created? 有关详细解答,请参阅此文章: 如果没有创建该类的对象,则类的静态成员是否占用内存?

A static member is not associated with a specific instance. 静态成员与特定实例无关。

If you want different values of the member for each instance you should use instance members (remove the static keyword). 如果您想为每个实例使用不同的成员值,则应使用实例成员(删除static关键字)。

It's by definition- a static object is one that's shared by all instances of the class. 根据定义,静态对象是由类的所有实例共享的对象。 Regular members don't have this property. 普通会员没有这个属性。

That is the definition of static - one copy of the data exists. 这就是static的定义 - 存在一个数据副本。 It is separately stored, most likely along with all the other static data of the library or application. 它是单独存储的,很可能与库或应用程序的所有其他静态数据一起存储。

因为这就是static意味着在这种情况下。

因为类静态成员分别存储在BSS部分中,所以类的每个实例都具有相同的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何初始化属于类的成员并且与它们所在的类具有相同类型的静态对象? - How are static objects, that are members of a class and that are of the same type as the class they are in, initialized? C++ 模板 Class 和 Static 成员 - 所有类型的 class 相同 - C++ Template Class with Static Members - Same for all types of the class 静态数据成员是否在所有类对象之前初始化? - Are static data members initialized before all class objects? 全局对象和类的静态成员 - Global objects and static members of class 为什么对向量中类成员的引用指向不同对象的相同值? - why references to members of a class in a vector point to the same value for different objects? C ++中的静态对象是类的静态数据成员还是静态方法? - Are the static data members and static methods of a class in C++ static objects? 具有所有成员和方法的C ++类静态 - C++ class with all members and methods static 有没有一种快速的方法可以将 class 的所有 static 成员归零? - Is there a quick way to zero all the static members of a class? 同一类的对象具有不同的类成员选择(C ++) - Objects of same class having varying selection of the class members (C++) 与类定义相同类型的静态constexpr成员(其他详细信息) - Static constexpr members of same type as class defined (additional details)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM