头文件的优点/缺点
与 Java 等语言相比,在 C 或 C++ 等语言中使用头文件有哪些优点和缺点?我认为类应该从外向内设计,因此最好有头文件,而不必费力地了解实现细节。然而,话又说回来,每个函数声明都会在两个文件中重复。如果今天发明了 C 和 C++,它们会使用头文件吗?这种机制是否已经过时或有必要?
What are the advantages and disadvantages of using header files in a language like C or C++ verses a language like Java? I think classes should be designed from the outside in, so it is nice to have header files and not have to wade through implementation details. However, then again, each function declaration is duplicated across two files. If C and C++ were invented today would they use header files? Is this mechanism outdated or necessary?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
摘自 Eric Lippert 的相关博客文章,谁说得很好:
这与 C#(博客文章讨论的内容)和 Java 等语言形成鲜明对比,后者是近亲。
Taken from a related blog post by Eric Lippert, who puts it very well:
This is in contrast to languages such as C# (about which the blog post is) and Java, which is a pretty close relative.
将接口和实现分开仍然是一个好主意。但这不一定是物理分离。在Java中你可以从javadoc中看到接口。 Java IDE 通常可以显示 API 结构,并且可以折叠块。没有令人信服的理由需要物理隔离。 C 是几十年前发明的,所以我们不需要挑剔它。
It's still a good idea to separate interface and implementation. But it doesn't have to be physical separation. In Java you can see the interface from javadoc. Java IDEs usually can display API structures, and they can fold blocks. There is no compelling reasons that require physical separation. C was invented decades ago so we don't need to pick on it.
简而言之,在 C 或 C++ 中,头文件允许不同的文件共享通用的定义或声明。
在Java中,一切都是对象,因此除了对象之外不存在共享任何东西的概念。每个对象都是一个文件;如果您想访问该对象,请导入该文件。
Briefly, in C or C++ header files allow different files to share common definitions or declarations.
In Java everything is an object, so there's no concept of sharing anything except objects. Each object is one file; if you want to access the object, you import the file.