c++要前向申明而java,为什么C ++需要通过头或语句的前向声明,Java不需要?

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 it can be implemented as a single-pass compiler, which means 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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值