这些语言中这些术语的含义是什么?为什么(如果有的话)这些语言在这方面存在差异?
这些语言中这些术语的含义是什么?为什么(如果有的话)这些语言在这方面存在差异?
一个声明是一种表明“这里有个东西的名字和类型,但我不会再告诉你更多信息”的语句。
一个定义是一种表明“这里有个东西的名字和确切内容”的语句。对于函数来说,这就是函数体;对于全局变量来说,这就是该变量所在的翻译单元。
初始化是指在定义时为变量赋予初始值的过程。有些语言会自动将所有变量初始化为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
};
我不太熟悉你所问的其他语言,但我认为它们在声明和定义之间没有太大区别。 C#和Java对所有对象都有默认初始化 - 如果您不明确初始化它,则所有内容都将初始化为0、false或null。 Python甚至更加宽松,因为变量在使用前不需要声明。由于绑定是在运行时解析的,所以也没有真正需要函数声明。