返回信息流第一点是67页里,说:
However, there can be only one definition (Section 2.3.5, p. 52) for any variable in a C++ program. A definition allocates storage; all uses of the variable must refer to the same storage. Because, by default, const objects are local to the file in which they are defined, it is legal to put their definition in a header file.
最后一句的因果关系我没搞清楚,为什么 const objects are local to the file in which they are defined,就 it is legal to put their definition in a header file.
第二点是最后一段:When a const is initialized by a value that is not a constant expression, then it should not be defined in header file. Instead, as with any other variable, the const should be defined and initialized in a source file.
还是对因果关系不懂。为什么When a const is initialized by a value that is not a constant expression,就有it should not be defined in header file.
谢谢!
这是一条镜像帖。来源:北邮人论坛 / cpp / #19784同步于 2009/3/3
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖
不明白C++ Primer2.9.1节上的一个问题
simon2062
2009/3/3镜像同步13 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
【 在 simon2062 的大作中提到: 】
: 第一点是67页里,说:
: However, there can be only one definition (Section 2.3.5, p. 52) for any variable in a C++ program. A definition allocates storage; all uses of the variable must refer to the same storage. Because, by default, const objects are local to the file in which they are defined, it is legal to put their definition in a header file.
: 最后一句的因果关系我没搞清楚,为什么 const objects are local to the file in which they are defined,就 it is legal to put their definition in a header file.
: ...................
你问的是 原因的原因,求高人解答吧
1. 说得很清楚,因为const的变量的作用域只在当前文件中有效。
因此,假设有a.cc和b.cc两个文件,以及A.h一个头文件。
并且两个.cc文件都include A.h
在A.h中有 const int bbb = 1;
则相当于在a.cc中有 const int bbb = 1;
且在b.cc中有 const int bbb = 1;
由于a.cc和b.cc是两个文件,因此定义在其中的两个bbb,是两个变量,并不会指定在同一片内存区域。
当把a.cc和b.cc放在一起编译的时候,并不会引起冲突。
2. 还没有看明白你的意思@@
在vc2005编译器里,如果A.h包含const int a = 1;b.h和c.h都包含A.h,再由d.cpp包含b.h和c.h会报重复定义错误
【 在 ericyosho 的大作中提到: 】
: 1. 说得很清楚,因为const的变量的作用域只在当前文件中有效。
: 因此,假设有a.cc和b.cc两个文件,以及A.h一个头文件。
: 并且两个.cc文件都include A.h
: ...................
你的一起编译指的链接是吧...sorry
【 在 ericyosho 的大作中提到: 】
: 那当然会报重复定义啦。
: 你等于是在d.cpp里面写了两遍 const int a = 1;
: 不报错就奇怪了。
谢谢!
1.那么在a.cc和b.cc中要使用bbb,只需要写明extern const int bbb,是吗?
另一个问题是,既然是const了,又不会去修改它的值,那么指到同一片区域有什么问题。
2.我不清楚的就是为什么如果const变量不是用常量表达式初始话,它就不应该在头文件中定义。
【 在 ericyosho 的大作中提到: 】
: 1. 说得很清楚,因为const的变量的作用域只在当前文件中有效。
: 因此,假设有a.cc和b.cc两个文件,以及A.h一个头文件。
: 并且两个.cc文件都include A.h
: ...................
不是,你在a.cc和b.cc中要使用bbb,只要#include <A.h>就可以了。
【 在 simon2062 的大作中提到: 】
: 谢谢!
: 1.那么在a.cc和b.cc中要使用bbb,只需要写明extern const int bbb,是吗?
: 另一个问题是,既然是const了,又不会去修改它的值,那么指到同一片区域有什么问题。
: ...................
恩。明白了第一个问题的用法。
但是还是对这两个问题的原因不清楚。
1。既然是const了,又不会去修改它的值,那么指到同一片区域有什么问题?
2。为什么如果const变量不是用常量表达式初始话,它就不应该在头文件中定义?
【 在 ericyosho 的大作中提到: 】
: 不是,你在a.cc和b.cc中要使用bbb,只要#include <A.h>就可以了。