在全局作用域(第 2.3.6 节)里定义非 const 变量时,它在整个程序中都可以访问。我们可以把一个非 const 变更定义在一个文件中,假设已经做了合适的声明,就可在另外的文件中使用这个变量:
// file_1.cc int counter; // definition // file_2.cc extern int counter; // uses counter from file_1 ++counter; // increments counter defined in file_1
(为什么在FILE2.CC不能直接用COUNTER,而需要加一个extern int,因为他们是分别编译的,如果嫌编译了FILE2,这时会因为没有申明counter报错。)
与其他变量不同,除非特别说明,在全局作用域声明的 const 变量是定义该对象的文件的局部变量。此变量只存在于那个文件中,不能被其他文件访问。
通过指定 const 变更为 extern,就可以在整个程序中访问 const 对象:
// file_1.cc // defines and initializes a const that is accessible to other files extern const int bufSize = fcn(); // file_2.cc extern const int bufSize; // uses bufSize from file_1 // uses bufSize defined in file_1 for (int index = 0; index != bufSize; ++index)
枚举成员值可以是不唯一的。
// point2d is 2, point2w is 3, point3d is 3, point3w is 4 enum Points { point2d = 2, point2w, point3d = 3, point3w };每个 enum 都定义了一种新的类型。和其他类型一样,可以定义和初始化 Points 类型的对象,也可以以不同的方式使用这些对象。枚举类型的对象的初始化或赋值,只能通过其枚举成员或同一枚举类型的其他对象来进行:
Points pt3d = point3d; // ok: point3d is a Points enumerator Points pt2w = 3; // error: pt2w initialized with int pt2w = polygon; // error: polygon is not a Points enumerator pt2w = pt3d; // ok: both are objects of Points enum type
注意把 3 赋给 Points 对象是非法的,即使 3 与一个 Points 枚举成员相关联。
C++ 是一种静态类型语言:变量和函数在使用前必须先声明。变量可以声明多次但是只能定义一次。定义变量时就进行初始化几乎总是个好主意。