类静态类型初始化 [英] Class static type initialization

查看:98
本文介绍了类静态类型初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我只是有一个问题,在c ++ 11中为什么必须指定静态成员的类型才能为其分配值?

So I just had a question, In c++11 why do I have to specify the type of a static member to assign to it a value?

示例:

class Player
{
   static size_t numOfObj;
public:
   Player(){numOfObj++;}
   ~Player(){numOfObj--;}
}

size_t Player::numOfObj = 0;

在这种情况下,为什么我必须再次指定 numOfObj 的类型为 size_t ,我不能只做 Player :: numOfObj = 0; 由于

In this case why do I have to specify again that numOfObj is of type size_t, can't I just do Player::numOfObj = 0; due to it being already declared?

预先感谢。

推荐答案

size_t Player :: numOfObj = 0; 是定义的语法。 (非内联)静态变量必须在一个翻译单元中精确定义一次。

size_t Player::numOfObj = 0; is syntax for definition. A (non-inline) static variable must be defined exactly once in exactly one translation unit. Not more, and not less (unless the variable is unused).


我不能只是做Player :: numOfObj = 0;因为已经被声明了?

can't I just do Player::numOfObj = 0; due to it being already declared?

您可以这样做。但是不在命名空间范围内,因为那是表达式语句的语法。表达式语句可能不在名称空间范围内。仅在块范围内允许它们。该表达式的含义是分配了变量的值。赋值可以根据您的喜好(在类型为非常量且可赋值的情况下)进行多次转换,并且可以使用任意数量的转换单位。

You can do that. But not in the namespace scope because that is syntax of an expression statement. Expression statements may not be in the namespace scope. They are allowed only in a block scope. The meaning of this expression is that the value of the variable is assigned. Assignments can be done as many times and in as many translation units as you like (as long as the type is non-const and assignable).

因此,如果定义包含该语法与已经具有另一种含义的语法会有冲突。那是不可取的。

So, if definition had this syntax, there would be conflict with the syntax already having another meaning. That would be undesirable.

这篇关于类静态类型初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆