A 定义是一个声明,表示“这是某物的名称以及它到底是什么”。对于函数来说,这就是函数体;对于全局变量,这将是变量所在的翻译单元。
An 初始化是一个定义,其中变量还被赋予初始值。某些语言自动将所有变量初始化为某个默认值,例如 0、false 或 null。有些(如 C/C++)并非在所有情况下都如此:所有全局变量都是默认初始化的,但堆栈上的局部变量和堆上动态分配的变量不是默认初始化的 - 它们具有未定义的内容,因此您必须显式初始化他们。 C++ 也有默认构造函数,这是另一种蠕虫病毒。
例子:
// In global scope:
extern int a_global_variable; // declaration of a global variable
int a_global_variable; // definition of a global variable
int a_global_variable = 3; // definition & initialization of a global variable
int some_function(int param); // declaration of a function
int some_function(int param) // definition of a function
{
return param + 1;
}
struct some_struct; // declaration of a struct; you can use pointers/references to it, but not concrete instances
struct some_struct // definition of a struct
{
int x;
int y;
};
class some_class; // declaration of a class (C++ only); works just like struct
class some_class // definition of a class (C++ only)
{
int x;
int y;
};
enum some_enum; // declaration of an enum; works just like struct & class
enum some_enum // definition of an enum
{
VALUE1,
VALUE2
};