我不明白两者的意义。
当前回答
为了理解名词,我们先来看看动词。
声明- - - - - - 宣布:正式宣布;宣告
定义- - - - - - 清晰完整地显示或描述(某人或某事
所以,当你声明某物时,你只需告诉它是什么。
// 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;
初始化意味着为各个变量或对象分配内存。
从C99标准,6.7(5):
声明指定一组标识符的解释和属性。标识符的定义是该标识符的声明:
对于一个对象,使存储空间为该对象保留; 对于函数,包括函数体; 类的(唯一)声明 标识符。
来自c++标准3.1(2):
声明是定义,除非它声明了一个函数而没有指定函数体,它包含extern说明符或链接规范,但既没有初始化式也没有函数体,它在类声明中声明了静态数据成员,它是类名声明,或者它是typedef声明,using-declaration,或using-directive。
下面是一些例子。
有趣的是(也许不是,但我有点惊讶)typedef int myint;是C99中的定义,但在c++中只是声明。
从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
定义意味着实际编写的函数,声明意味着简单的声明函数 如。
void myfunction(); //this is simple declaration
and
void myfunction()
{
some statement;
}
这是函数myfunction的定义
可执行文件的生成阶段:
(1)预处理器->(2)转换器/编译器->(3)链接器
在第二阶段(译者/编译器),我们代码中的声明语句告诉编译器,这些东西我们将在未来使用,你可以稍后找到定义,意思是:
译者确定:什么是什么?方法声明
(3)阶段(链接器)需要定义来绑定事物
链接器确定:哪里是什么?方法定义