我不明白两者的意义。
当前回答
c++标准3.1节:
声明将名称引入到翻译单元中,或者重新声明前一个翻译单元中引入的名称 声明。声明指定这些名称的解释和属性。
下一段声明(强调是我的)声明是一种定义,除非……
... 它声明一个函数而不指定函数体:
void sqrt(double); // declares sqrt
... 它在类定义中声明一个静态成员:
struct X
{
int a; // defines a
static int b; // declares b
};
... 它声明了一个类名:
class Y;
... 它包含没有初始化式或函数体的extern关键字:
extern const int i = 0; // defines i
extern int j; // declares j
extern "C"
{
void foo(); // declares foo
}
... Or是类型定义或using语句。
typedef long LONG_32; // declares LONG_32
using namespace std; // declares std
现在,理解声明和定义之间的区别很重要的一个重要原因是:一个定义规则。c++标准第3.2.1节:
任何翻译单元都不能包含任何变量、函数、类类型、枚举类型或模板的多个定义。
其他回答
在这里找到类似的答案:C语言的技术面试问题。
声明为程序提供了一个名称;定义提供程序中实体(例如类型、实例和函数)的唯一描述。声明可以在给定的作用域中重复,它在给定的作用域中引入一个名称。
声明是定义,除非:
声明声明了一个函数,但没有指定函数体, 声明包含一个extern说明符,没有初始化式或函数体, 声明是没有类定义的静态类数据成员的声明, 声明是类名定义,
定义是声明,除非:
定义定义一个静态类数据成员, Definition定义一个非内联成员函数。
声明:“在某处,存在一个foo。”
定义:“…就是这儿!”
声明说"这个东西存在于某个地方"
int sampleFunc(); // function
extern int car; // variable
定义说,这个东西存在于这里;为它留下记忆"
int sampleFunc() {} // function
int car; // variable
在定义对象时,初始化是可选的,并表示“这是这个东西的初始值”:
int car = 0; // variable
《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 i;
或者将名称、返回类型和参数类型赋给一个没有函数体的函数(在函数声明的情况下),例如:
int max(int, int);
而定义意味着给变量赋值(在变量定义的情况下),例如:
i = 20;
或者为函数提供/添加函数体(功能)被称为函数定义,例如:
int max(int a, int b)
{
if(a>b) return a;
return b;
}
许多时间声明和定义可以一起完成:
int i=20;
and:
int max(int a, int b)
{
if(a>b) return a;
return b;
}
在上述情况下,我们定义并声明变量i和函数max()。