注册 登录
编程论坛 C++教室

关于const static数据成员

baobaoisme 发布于 2011-08-12 15:29, 1378 次点击
“const static数据成员在类的定义体中初始化时,该数据成员仍必须在类的定义体之外进行定义。”看书看到这句注解不解。
const static数据成员的初始化例子:static const int period=30;
我的问题是,为什么在类的定义体中初始化后,还要在类的定义体外进行定义?c++的严格规定吗?为什么我没有在类定义体外进行定义,但是编译的时候却没有错误?求解
8 回复
#2
tisyang2011-08-12 15:41
翻译的不好,估计,去找英文原文吧。
#3
baobaoisme2011-08-12 16:10
#4
specilize2011-08-12 19:37
首先,static数据成员并不是由某个对象所拥有,而是隶属于类,也就是说为某个对象分配空间时并不为static对象分配空间,所以static必须在类的外部进行定义,毕竟定义才分配存储空间嘛,至于const static数据成员不用再类外进行定义,我觉得是编译器的特殊处理吧,个人理解而已。
#5
玩出来的代码2011-08-12 20:11
编译,然后是链接、
#6
玩出来的代码2011-08-13 11:07
原来static const member挺有意思的。有兴趣看这个链接:http://
#7
baobaoisme2011-08-13 11:30
确实哦,看了看,很好,原来并不是书上翻译错误,楼上给的那个论坛这个问题的答案还有个外链,讲的超级好,确实是需要在类的外部定义,在类的内部const static 类型即使赋字面值常量也只能算是声明,定义必须在外部进行。
http://publib.boulder.
If a static data member is of const integral or const enumeration type, you may specify a constant initializer in the static data member's declaration. This constant initializer must be an integral constant expression. Note that the constant initializer is not a definition. You still need to define the static member in an enclosing namespace.
非常感谢楼上各位回答。

[ 本帖最后由 baobaoisme 于 2011-8-13 17:17 编辑 ]
#8
玩出来的代码2011-08-13 11:52
C++iso标准有这样一段、

9.4 Static members
4 If a static data member is of const integral or const enumeration type, its declaration in the class
definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that
case, the member can appear in integral constant expressions. The member shall still be defined in a namespace
scope if it is used in the program and the namespace scope definition shall not contain an initializer.
这里也是说了在类中声明一个static const member,最后一句是说了必须在a nampspace scope中定义,不知道这个namespace scope是不是就是说任何一个名字空间。
#9
rjsp2011-08-13 16:22
以下是引用玩出来的代码在2011-8-13 11:07:09的发言:

原来static const member挺有意思的。有兴趣看这个链接:http://
长见识了,不错,顶,up
1