C++ const

来源:互联网 发布:yes风淘宝客程序下载 编辑:程序博客网 时间:2024/04/28 12:57

1. By Default, const Objects Are Local to a File

默认情况下,const对象是本地的

这是《C++ primary 5th》里的原文

When a const object is initialized from a compile-time constant, such as in our
definition of bufSize:

  1. const int bufSize = 512; // input buffer size  

the compiler will usually replace uses of the variable with its corresponding value during compilation. That is, the compiler will generate code using the value 512 in the places that our code uses bufSize.

To substitute the value for the variable, the compiler has to see the variable’s initializer. When we split a program into multiple files, every file that uses the const must have access to its initializer. In order to see the initializer, the variable must be defined in every file that wants to use the variable’s value (§ 2.2.2, p. 45). To support this usage, yet avoid multiple definitions of the same variable, const variables are defined as local to the file. When we define a const with the same name in multiple files, it is as if we had written definitions for separate variables in each file.

意思大概就是说,当我们定义了一个const对象时(必须初始化),编译器需要使用其相应的初始化值来代替我们定义的这个对象。为了得到初始化值,编译器需要访问initializer。根据(§ 2.2.2, p. 45),对象只能有一个定义。编译阶段,编译器就像调用者,我们的const对象对于编译器来说就是一个被调用者。当我们将程序拆分为多个文件时,如果同一个const 对象有多个定义,那么编译器将无法作出选择,也就无法开展编译工作。因此,为了满足每个const对象被初始化以及避免多重定义,const variables are defined as local to the file。当我们在多个文件中分别定义同名的const对象时,就像我们定义互不相干的对象一样。

Example:

#const_test.h

void printMsg();

#const_test.cpp

#include <iostream>extern int varx_global;extern const int varz_global;void printMsg(){    std::cout << "'varx_global' is " << varx_global << "." << std::endl;    std::cout << "'varz_global' is " << varz_global << "." << std::endl;}

#main.cpp

#include <iostream>#include "const_test.h"int varx_global = 2001;extern const int varz_global = 1998;//Without extern, the caller will be error with undifinedint main(){    printMsg();        /*    Output:        'varx_global' is 2001.        'vary_global' is 1998.    */    return 0;}

未完待续

0 0