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