C、C++、C#、Java 和 Python 中的声明、定义、初始化
上述每种语言中的术语含义是什么? 为什么这些语言在这方面有所不同(无论它们在哪里,如果有的话)?
What do the terms mean in each of the above languages? Why do the languages differ (wherever they do, if at all they do) in this respect?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
C/C++:
声明是一条声明,表示“这是某物的名称及其类型,但我不会告诉您更多有关它的信息”。
定义是一个声明,表示“这是某物的名称以及它到底是什么”。 对于函数来说,这就是函数体; 对于全局变量,这将是变量所在的翻译单元。
初始化是一种定义,其中变量还被赋予初始值。 某些语言自动将所有变量初始化为某个默认值,例如 0、false 或 null。 有些(如 C/C++)并非在所有情况下都如此:所有全局变量都是默认初始化的,但堆栈上的局部变量和堆上动态分配的变量不是默认初始化的 - 它们具有未定义的内容,因此您必须显式初始化他们。 C++ 也有默认构造函数,这是另一种蠕虫病毒。
示例:
我对您询问的其他语言不太熟悉,但我相信它们在声明和定义之间没有太大区别。 C# 和 Java 对所有对象都有默认初始化 - 如果您没有显式初始化,则所有对象都会初始化为 0、false 或 null。 Python 更加宽松,因为变量在使用之前不需要声明。 由于绑定是在运行时解析的,因此也不需要声明函数。
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:
I'm not as familiar with the other languages you asked about, but I believe they don't make much of a distinction between declarations and definitions. C# and Java have default initialization for all objects - everything is initialized to 0, false, or null if you don't explicitly initialize it. Python is even more lax, since variables don't need to be declared before they're used. Since bindings are resolved at runtime, there's no real need for declarations of functions, either.