是什么定义和声明之间的区别

是什么定义和声明之间的区别

本文介绍了是什么定义和声明之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为标题所说,两者的含义逃避我。

As title says, the meaning of both eludes me.

推荐答案

A 声明引入了一个标识符和描述它的类型,无论是类型,对象或函数。一个声明为 编译器需要什么以接受该标识符引用。这些声明:

A declaration introduces an identifier and describes its type, be it a type, object, or function. A declaration is what the compiler needs to accept references to that identifier. These are declarations:

extern int bar;
extern int g(int, int);
double f(int, double); // extern can be omitted for function declarations
class foo; // no extern allowed for type declarations

A 定义实际实例/实现此标识。它的什么链接器需要,以引用链接到这些实体。这些是对应于上述的声明定义:

A definition actually instantiates/implements this identifier. It's what the linker needs in order to link references to those entities. These are definitions corresponding to the above declarations:

int bar;
int g(int lhs, int rhs) {return lhs*rhs;}
double f(int i, double d) {return i+d;}
class foo {};

一个定义可以在声明的地方使用。

A definition can be used in the place of a declaration.

标识符可以的声明的。因此,下面是合法的C和C ++:

An identifier can be declared as often as you want. Thus, the following is legal in C and C++:

double f(int, double);
double f(int, double);
extern double f(int, double); // the same as the two above
extern double f(int, double);

但是,必须的定义的一次。如果忘记定义的已宣告某处引用的东西,那么链接器不知道该怎么引用链接并抱怨缺少符号。如果定义的东西不止一次,则链接不知道的的定义链接到引用和抱怨重复的符号。

However, it must be defined exactly once. If you forget to define something that's been declared and referenced somewhere, then the linker doesn't know what to link references to and complains about a missing symbols. If you define something more than once, then the linker doesn't know which of the definitions to link references to and complains about duplicated symbols.

由于争论什么是类的声明的对一类的定义在C ++ 的不断上来(在回答和评论其他问题),我会粘贴引自C ++标准在这里。结果
在3.1 / 2,C ++ 03说道:

Since the debate what is a class declaration vs. a class definition in C++ keeps coming up (in answers and comments to other questions) , I'll paste a quote from the C++ standard here.
At 3.1/2, C++03 says:

一个声明是一个定义,除非它[...]是一个类名的声明[...]

3.1 / 3则给出了几个例子。他们当中:

3.1/3 then gives a few examples. Amongst them:


[Example: [...]
struct S { int a; int b; }; // defines S, S::a, and S::b [...]
struct S; // declares S
—end example

要总结:C ++标准认为结构X; 是一个的声明结构X {} ; A的定义的。 (换句话说, 前进宣言名不副实后,因为没有其他形式的C级声明++)。

To sum it up: The C++ standard considers struct x; to be a declaration and struct x {}; a definition. (In other words, "forward declaration" a misnomer, since there are no other forms of class declarations in C++.)

感谢谁在一个挖出来的实际的章节和诗句他答案。

Thanks to litb (Johannes Schaub) who dug out the actual chapter and verse in one of his answers.

这篇关于是什么定义和声明之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 19:34