English 中文(简体)
在C、C++、C#、Java和Python中的声明、定义、初始化。 [关闭]
原标题:
  • 时间:2008-11-21 19:01:04
  •  标签:
问题回答

C/C++:

A declaration is a statement that says "here is the name of something and the type of thing that it is, but I m not telling you anything more about it".

A definition is a statement that says "here is the name of something and what exactly it is". For functions, this would be the function body; for global variables, this would be the translation unit in which the variable resides.

An initialization is a definition where the variable is also given an initial value. Some languages automatically initialize all variables to some default value such as 0, false, or null. Some (like C/C++) don t in all cases: all global variables are default-initialized, but local variables on the stack and dynamically allocated variables on the heap are NOT default initialized - they have undefined contents, so you must explicitly initialize them. C++ also has default constructors, which is a whole nother can of worms.

Examples:


// 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甚至更加灵活,因为变量不需要在使用之前声明。由于绑定在运行时解析,因此对于函数,也没有真正需要声明。





相关问题
热门标签