我不明白两者的意义。


当前回答

你不能用最一般的术语说,声明是一个没有分配存储空间的标识符,而定义实际上是从声明的标识符分配存储空间吗?

一个有趣的想法是:只有类或函数与类型信息链接起来,模板才能分配存储空间。那么模板标识符是声明还是定义呢?它应该是一个声明,因为没有分配存储空间,您只是在对模板类或函数进行“原型化”。

其他回答

从C99标准,6.7(5):

声明指定一组标识符的解释和属性。标识符的定义是该标识符的声明:

对于一个对象,使存储空间为该对象保留; 对于函数,包括函数体; 类的(唯一)声明 标识符。

来自c++标准3.1(2):

声明是定义,除非它声明了一个函数而没有指定函数体,它包含extern说明符或链接规范,但既没有初始化式也没有函数体,它在类声明中声明了静态数据成员,它是类名声明,或者它是typedef声明,using-declaration,或using-directive。

下面是一些例子。

有趣的是(也许不是,但我有点惊讶)typedef int myint;是C99中的定义,但在c++中只是声明。

声明:“在某处,存在一个foo。”

定义:“…就是这儿!”

为了理解名词,我们先来看看动词。

声明- - - - - - 宣布:正式宣布;宣告

定义- - - - - - 清晰完整地显示或描述(某人或某事

所以,当你声明某物时,你只需告诉它是什么。

// declaration
int sum(int, int);

这一行声明了一个名为sum的C函数,它接受两个int类型的参数并返回一个int。但是,您还不能使用它。

当你提供它的实际工作方式时,这就是它的定义。

// definition
int sum(int x, int y)
{
    return x + y;
}

《K&R》(第二版)中有一些非常明确的定义;这有助于把它们放在一个地方,并作为一个整体来阅读:

"Definition" refers to the place where the variable is created or assigned storage; "declaration" refers to the places where the nature of the variable is stated but no storage is allocated. [p. 33] ... It is important to distinguish between the declaration of an external variable and its definition. A declaration announces the properties of a variable (primarily its type); a definition also causes storage to be set aside. If the lines int sp; double val[MAXVAL] appear outside of any function, they define the external variables sp and val, cause storage to be set aside, and also serve as the declaration for the rest of that source file. On the other hand, the lines extern int sp; extern double val[]; declare for the rest of the source file that sp is an int and that val is a double array (whose size is determined elsewhere), but they do not create the variables or reserve storage for them. There must be only one definition of an external variable among all the files that make up the source program. ... Array sizes must be specified with the definition, but are optional with an extern declaration. [pp. 80-81] ... Declarations specify the interpretation given to each identifier; they do not necessarily reserve storage associated with the identifier. Declarations that reserve storage are called definitions. [p. 210]

声明是在未分配值或对象的情况下创建原语或对象引用变量或方法。 int; Final int a;

定义意味着分别为值或对象赋值 Int a =10;

初始化意味着为各个变量或对象分配内存。