我一直试图弄清楚为什么 C++ 让我疯狂地键入 NULL
。前几天它突然袭击了我;多年来,我一直在用 Java 输入 null
(小写)。现在突然间我在用 C++ 编程,而那一小块肌肉内存让我发疯了。
Wikiperipatetic 将 C++ NULL 定义为 stddef 的一部分:
A macro that expands to a null pointer constant. It may be defined as ((void*)0), 0 or 0L depending on the compiler and the language.
Sun 的文档告诉我关于 Java 的“空文字”:
The null type has one value, the null reference, represented by the literal null, which is formed from ASCII characters. A null literal is always of the null type.
所以这一切都很好。我知道空指针引用是什么,感谢您的编译器注释。现在我对 Java 中文字的概念有点模糊,所以我继续阅读......
A literal is the source code representation of a fixed value; literals are represented directly in your code without requiring computation.
There's also a special null literal that can be used as a value for any reference type. null may be assigned to any variable, except variables of primitive types. There's little you can do with a null value beyond testing for its presence. Therefore, null is often used in programs as a marker to indicate that some object is unavailable.
好的,我想我现在明白了。在 C++ 中,NULL 是一个宏,它在编译时计算为空指针常量。在 Java 中,null 是一个固定值,也可以分配任何非原始值;非常适合在方便的 if 语句
中进行测试。
Java 没有指针,所以我可以理解为什么它们将 null 保留为一个简单的值,而不是任何花哨的值。 但是为什么java决定将所有大写的NULL
改为null
?
此外,我这里有什么遗漏吗?
最佳答案
NULL
是一个预处理指令标识符,按照惯例,应该全部大写。null
是一个 language litteral 表示一个常量值,并且按照惯例应该都更低(就像true
或假
)。
关于java - C++ 中的 NULL 和 Java 中的 null 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2960193/