C++ 中的定义和声明有什么区别?


在 C++ 中,声明和定义经常混淆。声明意味着(在 C 中)您正在告诉编译器类型、大小和对于函数声明、类型和程序中任何变量的参数大小,或用户自定义类型或函数。在声明时,不会为任何变量在内存中保留空间。

而定义意味着,除了声明所做的一切之外,还另外在内存中保留空间。您可以说“定义=声明+空间保留”。

以下是声明的示例 -

extern int a;                           // Declaring a variable a without defining it
struct _tagExample { int a; int b; };   // Declaring a struct
int myFunc (int a, int b);              // Declaring a function

以下是定义的示例 -

int a;
int b = 0;
int myFunc (int a, int b) { return a + b; }
struct _tagExample example;

更新于: 30-Jul-2019

2K+ 浏览

开启你的 职业生涯

完成课程并获得认证

开始学习
广告
© . All rights reserved.