我不明白两者的意义。
当前回答
c++ 11更新
由于我没有看到与c++ 11相关的答案,这里有一个。
声明是定义,除非声明了/n:
opaque enum - enum X: int; 模板参数-模板参数- MyArray 参数声明- x和y在int add(int x, int y); 别名声明-使用IntVector = std::vector<int>; - static_assert(sizeof(int) == 4, "Yikes!") 属性声明(实现定义的) 空声明;
以上列表从c++ 03继承的附加子句:
函数声明- add in int add(int x, int y); Extern说明符包含声明或链接说明符- Extern int a;或extern "C"{…}; 类中的静态数据成员-类C中的x{静态int x;}; 类/struct声明- struct Point; typedef int int; 使用声明-使用std::cout; 使用命名空间NS;
模板声明是一种声明。如果模板声明定义了函数、类或静态数据成员,那么模板声明也是定义。
以下例子来自于区分声明和定义的标准,我发现这些例子有助于理解它们之间的细微差别:
// except one all these are definitions
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
// all these are declarations
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 N::d
// specific to C++11 - these are not from the standard
enum X : int; // declares X with int as the underlying type
using IntVector = std::vector<int>; // declares IntVector as an alias to std::vector<int>
static_assert(X::y == 1, "Oops!"); // declares a static_assert which can render the program ill-formed or have no effect like an empty declaration, depending on the result of expr
template <class T> class C; // declares template class C
; // declares nothing
其他回答
你不能用最一般的术语说,声明是一个没有分配存储空间的标识符,而定义实际上是从声明的标识符分配存储空间吗?
一个有趣的想法是:只有类或函数与类型信息链接起来,模板才能分配存储空间。那么模板标识符是声明还是定义呢?它应该是一个声明,因为没有分配存储空间,您只是在对模板类或函数进行“原型化”。
当您使用extern存储类时,声明和定义的概念将形成一个陷阱,因为您的定义将位于其他位置,而您是在本地代码文件(页面)中声明变量。C和c++之间的一个区别是,在C中,声明通常在函数或代码页的开头完成。在c++中不是这样的。你可以在你选择的地方申报。
声明:“在某处,存在一个foo。”
定义:“…就是这儿!”
这听起来很俗气,但这是我能把这些条款直接记在脑子里的最好方法:
宣言:想象托马斯·杰斐逊发表演讲……“我在此声明这个foo在这个源代码中存在!!”
定义:想象一本字典,你正在查找Foo和它的实际意思。
可执行文件的生成阶段:
(1)预处理器->(2)转换器/编译器->(3)链接器
在第二阶段(译者/编译器),我们代码中的声明语句告诉编译器,这些东西我们将在未来使用,你可以稍后找到定义,意思是:
译者确定:什么是什么?方法声明
(3)阶段(链接器)需要定义来绑定事物
链接器确定:哪里是什么?方法定义
推荐文章
- 编程中的术语“上下文”?
- 通过SSH使用Eclipse完成远程项目
- int的最大值
- 什么是“参数依赖查找”(又名ADL,或“Koenig查找”)?
- 如何将文件指针(file * fp)转换为文件描述符(int fd)?
- C“int”的大小是2字节还是4字节?
- 多维数组如何在内存中格式化?
- printf()和puts()在C语言中的区别是什么?
- 断言是邪恶的吗?
- 下面这些短语在c++中是什么意思:0 -,default-和value-initialization?
- 有效,但毫无价值的语法在开关情况下?
- 有一个好的Valgrind Windows的替代品吗?
- gcc在哪里查找C和c++头文件?
- c++中size_t和int的区别是什么?
- 在C和c++中静态变量存储在哪里?