为什么类的静态成员对于所有对象都相同?
为什么我们不为不同的对象拥有不同的静态变量副本?
Why don't we have different copies of static variables for the different objects?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
为什么我们不为不同的对象拥有不同的静态变量副本?
Why don't we have different copies of static variables for the different objects?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(7)
因为那时他们将是实例成员。
静态成员的主要特征是它们由类的所有实例共享。
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.
因为 C++ 标准 (2003) 中的 $9.4.2/1 部分说,
由于标准本身决定了 C++ 是什么、不是什么,所以 C++ 就是这样设计的!
静态成员更像是全局对象。相同的副本属于所有对象!
有关详细答案,请参阅此帖子:如果没有创建类的对象,该类的静态成员会占用内存吗?
Because the section $9.4.2/1 from the C++ Standard (2003) says,
Since the Standard alone decides what C++ is, what not, so it's how C++ has been designed!
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?
静态成员不与特定实例关联。
如果您希望每个实例的成员具有不同的值,则应使用instance 成员(删除 static 关键字)。
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).
根据定义,静态对象是由类的所有实例共享的对象。普通会员没有这个属性。
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. It is separately stored, most likely along with all the other static data of the library or application.因为这就是
static
在该上下文中的含义。Because that's what
static
means in that context.由于类静态成员单独存储在 BSS 部分,因此类的每个实例都具有相同的值。
Because class static members are stored separately in BSS section, so every instance of a class has the same value.