我不明白两者的意义。
当前回答
这听起来很俗气,但这是我能把这些条款直接记在脑子里的最好方法:
宣言:想象托马斯·杰斐逊发表演讲……“我在此声明这个foo在这个源代码中存在!!”
定义:想象一本字典,你正在查找Foo和它的实际意思。
其他回答
定义意味着实际编写的函数,声明意味着简单的声明函数 如。
void myfunction(); //this is simple declaration
and
void myfunction()
{
some statement;
}
这是函数myfunction的定义
我最喜欢的例子是int Num = 5这里你的变量是1。定义为int 2。声明为Num和3。实例化值为5。我们
定义对象的类型,可以是内置的,也可以是类或结构。 声明一个对象的名字,这样任何有名字的东西都被声明了,包括变量、函数等。
类或结构允许您在以后使用时更改对象的定义方式。例如
可以声明没有特别定义的异构变量或数组。 在c++中使用偏移量可以定义一个没有声明名称的对象。
当我们学习编程时,这两个术语经常被混淆,因为我们经常同时做这两个。
从wiki.answers.com:
术语声明(在C语言中)意味着你告诉编译器关于类型,大小,如果是函数声明,任何变量的参数的类型和大小,或者程序中用户定义的类型或函数。在声明时,内存中不为任何变量保留空间。然而,编译器知道在这种类型的变量被创建的情况下要保留多少空间。
例如,以下是所有的声明:
extern int a;
struct _tagExample { int a; int b; };
int myFunc (int a, int b);
另一方面,定义意味着除了声明所做的所有事情之外,内存中还保留了空间。你可以说“DEFINITION = DECLARATION + SPACE RESERVATION”,下面是定义的例子:
int a;
int b = 0;
int myFunc (int a, int b) { return a + b; }
struct _tagExample example;
看到答案。
声明向编译器提供了一个符号名。定义是为符号分配空间的声明。
int f(int x); // function declaration (I know f exists)
int f(int x) { return 2*x; } // declaration and definition
从c++标准文档中添加定义和声明示例(来自3.1节声明和定义)
定义:
int a; // defines a
extern const int c = 1; // defines c
int f(int x) { return x+a; } // defines f and defines x
struct S { int a; int b; }; // defines S, S::a, and S::b
struct X { // defines X
int x; // defines non-static data member x
static int y; // DECLARES static data member y
X(): x(0) { } // defines a constructor of X
};
int X::y = 1; // defines X::y
enum { up, down }; // defines up and down
namespace N { int d; } // defines N and N::d
namespace N1 = N; // defines N1
X anX; // defines anX
声明:
extern int a; // declares a
extern const int c; // declares c
int f(int); // declares f
struct S; // declares S
typedef int Int; // declares Int
extern X anotherX; // declares anotherX
using N::d; // declares d