我不明白两者的意义。
当前回答
声明是在未分配值或对象的情况下创建原语或对象引用变量或方法。 int; Final int a;
定义意味着分别为值或对象赋值 Int a =10;
初始化意味着为各个变量或对象分配内存。
其他回答
从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
可执行文件的生成阶段:
(1)预处理器->(2)转换器/编译器->(3)链接器
在第二阶段(译者/编译器),我们代码中的声明语句告诉编译器,这些东西我们将在未来使用,你可以稍后找到定义,意思是:
译者确定:什么是什么?方法声明
(3)阶段(链接器)需要定义来绑定事物
链接器确定:哪里是什么?方法定义
声明:“在某处,存在一个foo。”
定义:“…就是这儿!”
我最喜欢的例子是int Num = 5这里你的变量是1。定义为int 2。声明为Num和3。实例化值为5。我们
定义对象的类型,可以是内置的,也可以是类或结构。 声明一个对象的名字,这样任何有名字的东西都被声明了,包括变量、函数等。
类或结构允许您在以后使用时更改对象的定义方式。例如
可以声明没有特别定义的异构变量或数组。 在c++中使用偏移量可以定义一个没有声明名称的对象。
当我们学习编程时,这两个术语经常被混淆,因为我们经常同时做这两个。
根据GNU C库手册(http://www.gnu.org/software/libc/manual/html_node/Header-Files.html)
在C语言中,声明仅仅提供函数或变量存在的信息并给出其类型。对于函数声明,还可以提供关于其参数类型的信息。声明的目的是允许编译器正确地处理对声明的变量和函数的引用。另一方面,定义实际上为变量分配存储空间,或者说明函数的功能。