问题描述
Java不会抱怨如果你不转发声明你的函数,而C + +抱怨。我知道C ++涉及预处理,但我想了解更多..
对象文件 >
Java编译器依赖于编译到其生成的字节码(.class)文件中的额外信息,而且您的代码使用它们,而C ++编译器不会将这种信息存储在编译对象代码(.obj)。
作为一种较老的语言,C ++依赖于程序编译和链接的C模型。这意味着对象文件主要包含代码和数据,只有足够的元数据需要将对象文件链接在一起(在运行时静态或动态)。因此,编译器依赖于在解析源代码时包含的头文件来了解代码引用的外部类类型,函数和变量。
这也意味着您的C ++代码的客户端需要您的代码的目标文件(.obj,.lib或.dll)和头文件,以便自己使用它们。
Java ,作为一种更现代的语言,将大量符号元数据存储到其生成的对象(.class)文件中,这允许编译器提取外部类类型,方法和代码在后续编译期间引用的变量。
这也意味着您的Java代码的客户端只需要您的代码的目标文件(.class或.jar)就可以使用它。
转发声明
Java编译器对源代码进行多次传递,这意味着您只需要声明/在代码中的一个地方定义一个变量或方法;因为编译器更努力地确定类型信息。
C ++,相反,定义为,编译器需要知道在源代码中使用的一个类,变量或方法的所有相关类型信息。这意味着您必须在代码中的实际对象定义之前提供该类型的声明信息。这是为什么使用头文件。
Java doesn't complain if you don't forward declare your functions, whereas C++ complains. I know C++ involves preprocessing but I want to understand more..
Object files
Java compilers rely on extra information that is compiled into the bytecode (.class) files they produce and which your code uses, while C++ compilers do not store this kind of information in the compiled object code (.obj) files they produces.
Being an older language, C++ relies on the "C model" of program compilation and linkage. This means that object files contain mostly code and data, with only enough metadata needed for object files to be linked together (either statically or dynamically at runtime). Consequently, the compiler relies on header files included while parsing your source code to know about the external class types, functions, and variables your code refers to.
This also means that clients of your C++ code need both the object files (.obj, .lib, or .dll) and header files for your code in order to use it themselves.
Java, being a more modern language, stores a lot of symbolic metadata into the object (.class) files it produces, which allows the compiler to extract the external class types, methods, and variables your code refers to during later compiles.
This also means that clients of your Java code only need the object files (.class or .jar) for your code in order to use it.
Forward declarations
Java compilers make multiple passes on the source code, which means that you only need to declare/defined a variable or method in one place within your code; forward declarations are not necessary because the compiler works harder to determine type information.
C++, in contrast, is defined so that the compiler needs to know all of the relevant type information about a class, variable, or method at the point it is used in your source code. This means that you have to provide that type declaration information before the actual object definition in your code. This is why header files are used.
这篇关于为什么C ++需要通过头或语句的前向声明,Java不需要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!