变量定义与声明的区别(2)

时间:2026-01-23

变量定义与声明的区别

Declarations and Definitions

As we'll see in Section 2.9 (p. 67), C++ programs typically are composed of many files. In order for multiple files to access the same variable, C++ distinguishes between declarations and definitions.

就像我们在2.9 (p. 67)节看到的一样,典型的C++程序通常会由好多文件组成。为了使不同的文件都可以访问同一个变量,C++会区分变量的声明

(declarations)和定义(definitions)。

A definition of a variable allocates storage for the variable and may also specify an initial value for the variable. There must be one and only one definition of a variable in a program.

变量的定义(definitions)会为这个变量分配存储空间,并且可能会为其指定一个初始化的值。在程序里,一个变量必须有一个,也只能有一处定义(definitions)。

A declaration makes known the type and name of the variable to the program.

A definition is also a declaration: When we define a variable, we declare its name and type. We can declare a name without defining it by using the extern keyword. A declaration that is not also a definition consists of the object's name and its type preceded by the keyword extern:

变量的声明(declarations)会将变量的类型和名称传达给程序。当然,定义(definitions)也是一种声明:当我们定义一个变量的时候,我们当然也声明了他的名称和类型。我们可以通过使用“extern”关键字来声明(declarations)一个变量,而不用定义(definitions)它。声明(declarations)的形式就是在对象(变量)的名字和类型前面,加上关键字“extern”:

An extern declaration is not a definition and does not allocate storage. In effect, it claims that a definition of the variable exists elsewhere in the program. A variable can be declared multiple times in a program, but it must be defined only once.

变量定义与声明的区别(2).doc 将本文的Word文档下载到电脑

精彩图片

热门精选

大家正在看

× 游客快捷下载通道(下载后可以自由复制和排版)

限时特价:4.9 元/份 原价:20元

支付方式:

开通VIP包月会员 特价:19元/月

注:下载文档有可能“只有目录或者内容不全”等情况,请下载之前注意辨别,如果您已付费且无法下载或内容有问题,请联系我们协助你处理。
微信:fanwen365 QQ:370150219