我不明白两者的意义。
当前回答
从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
其他回答
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节:
任何翻译单元都不能包含任何变量、函数、类类型、枚举类型或模板的多个定义。
当您使用extern存储类时,声明和定义的概念将形成一个陷阱,因为您的定义将位于其他位置,而您是在本地代码文件(页面)中声明变量。C和c++之间的一个区别是,在C中,声明通常在函数或代码页的开头完成。在c++中不是这样的。你可以在你选择的地方申报。
声明说"这个东西存在于某个地方"
int sampleFunc(); // function
extern int car; // variable
定义说,这个东西存在于这里;为它留下记忆"
int sampleFunc() {} // function
int car; // variable
在定义对象时,初始化是可选的,并表示“这是这个东西的初始值”:
int car = 0; // variable
这听起来很俗气,但这是我能把这些条款直接记在脑子里的最好方法:
宣言:想象托马斯·杰斐逊发表演讲……“我在此声明这个foo在这个源代码中存在!!”
定义:想象一本字典,你正在查找Foo和它的实际意思。
根据GNU C库手册(http://www.gnu.org/software/libc/manual/html_node/Header-Files.html)
在C语言中,声明仅仅提供函数或变量存在的信息并给出其类型。对于函数声明,还可以提供关于其参数类型的信息。声明的目的是允许编译器正确地处理对声明的变量和函数的引用。另一方面,定义实际上为变量分配存储空间,或者说明函数的功能。