Some Const Objects Are Defined in Headers

 

Some Const Objects Are Defined in Headers

首先明确一点:const型变量的作用域为其定义的文件,在其它文件中无法调用。

example:


 

通常来说,const型的表达式是指其值能够在编译是确定的表达式。为了使不同的文件使用相同的const值,就要使得const的定义在每一个文件中都可见,因此要将其放在头文件中。因为const的作用于为当前文件,因此将其放在头文件中不会导致重复定义的错误。(一般情况下头文件中只放声明部分而不放定义部分,因为头文件可能会被多个文件调用从而导致重复定义)。

非常重要的一点是,当我们将const型变量定义在头文件中时,每一个文件都将有一个自己的const变量,名称相同、值也相同。

< C++ Primer >:

Recall that by default a const variable is local to the file in which it is defined .As we shall now see, the reason for this default is to allow const variables to be defined in header files.

In C++ there are places where constant expression is required. For example, the initialize of an enumerator must be a constant expression. We ‘ll see other cases that require constant expressions in later chapters.

Generally speaking, a const expression is an expression that the compiler can evaluate at compile-time. A const variable of integral type may be a constant expression when it is itself initialized from a constant expression. However, for the const to be a constant expression, the initialize must be visible to the compiler. To allow multiple files to use the same constant value, the const and its initialize must be visible in each file. To make the initialize visible, we normally define such consts inside a header file. That way the compiler can see the initialize whenever the const is used.

However, there can be only one definition for any variable in a C++ program. A definition allocates storage; all uses of the variable must be 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.

There is one important implication of this behavior. When we define a const in a header file, every source file that includes that header has its own const variable with the same name and value.

When the const is initialized by a constant expression, then we are guaranteed that all the variables will have the same value. Moreover, in practice, most compilers will replace any use of such const variables by their corresponding constant expression at compile time. So, in practice, there won’t be any storage used to hold const variables that are initialized by constant expressions.

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. An extern declaration for that const should be made in the header, enabling multiple files to share that variable.

原文地址:https://www.cnblogs.com/johnpher/p/2570624.html