我不明白两者的意义。
当前回答
宣言
声明告诉编译器a 程序元素或名称存在。一个 声明引入一个或多个 命名到程序中。声明可以 在一个程序中出现一次以上。 因此,类,结构, 枚举类型等 用户定义的类型可以声明为 每个编译单元。
定义
定义指定哪些代码或数据 名称描述。名称必须为 在使用之前声明。
其他回答
我最喜欢的例子是int Num = 5这里你的变量是1。定义为int 2。声明为Num和3。实例化值为5。我们
定义对象的类型,可以是内置的,也可以是类或结构。 声明一个对象的名字,这样任何有名字的东西都被声明了,包括变量、函数等。
类或结构允许您在以后使用时更改对象的定义方式。例如
可以声明没有特别定义的异构变量或数组。 在c++中使用偏移量可以定义一个没有声明名称的对象。
当我们学习编程时,这两个术语经常被混淆,因为我们经常同时做这两个。
当您使用extern存储类时,声明和定义的概念将形成一个陷阱,因为您的定义将位于其他位置,而您是在本地代码文件(页面)中声明变量。C和c++之间的一个区别是,在C中,声明通常在函数或代码页的开头完成。在c++中不是这样的。你可以在你选择的地方申报。
《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]
为了理解名词,我们先来看看动词。
声明- - - - - - 宣布:正式宣布;宣告
定义- - - - - - 清晰完整地显示或描述(某人或某事
所以,当你声明某物时,你只需告诉它是什么。
// declaration
int sum(int, int);
这一行声明了一个名为sum的C函数,它接受两个int类型的参数并返回一个int。但是,您还不能使用它。
当你提供它的实际工作方式时,这就是它的定义。
// definition
int sum(int x, int y)
{
return x + y;
}
声明是在未分配值或对象的情况下创建原语或对象引用变量或方法。 int; Final int a;
定义意味着分别为值或对象赋值 Int a =10;
初始化意味着为各个变量或对象分配内存。