C++ 头文件,代码分离 [英] C++ Header Files, Code Separation

查看:33
本文介绍了C++ 头文件,代码分离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 C++ 新手,我有一些关于代码分离的一般性问题.我目前在一个文件中构建了一个小型应用程序.我现在要做的是将其转换为单独的文件,以便它们包含类似的代码或诸如此类的东西.我现在真正的问题是,我怎么知道如何分开事物?代码应该分开的不可见边距是多少?

I am new to C++ and I had a few general questions about code separation. I have currently built a small application, all in one file. What I want to do now is convert this into separate files such that they contain similar code or whatnot. My real question right now is, how do I know how to separate things? What is the invisible margin that code should be separated at?

另外,头文件有什么意义?是否转发声明方法和类,以便我可以在编译期间将它们包含在链接器中之前在我的代码中使用它们?

Also, what's the point of header files? Is it to forward declare methods and classes so I can use them in my code before they are included by the linker during compilation?

任何对方法或最佳实践的见解都会很棒,谢谢!

Any insight into methods or best practises would be great, thanks!

推荐答案

头文件应该包含类和函数声明.

Header files should contain class and function declarations.

源文件包含类和函数定义.

Source files contain class and function definitions.

标准做法(即更容易阅读)每个头文件有一个声明,每个源文件有一个定义,但对于较小的(阅读更简单的帮助程序)对象,您有时会将它们与相关的更实质性的对象组合在一起.

It is standard practice (i.e. read easier) to have one declaration per header file and one definition per source file, though for small (read simpler helper) objects you sometimes group them with related more substantial objects.

Menu.h:     Contains the Menu declaration.
Menu.cpp:   Contains the Menu definition.

头文件包含声明的原因是您可以从多个源文件中包含它们,因此每个源文件对每个类和函数都有完全相同的定义.

The reason header files contain the declarations is so that you can include them from multiple source files and thus each source file has exactly the same definition of each class and function.

这样考虑:
如果您没有头文件,那么您需要在每个源文件中都有类和/或函数声明(没有)定义,这意味着每个文件中都有相同声明的副本.因此,如果您修改一个类,您需要在每个文件中进行相同的修改.通过使用头文件,您可以将声明放在一个位置,因此只需修改一个对象.

Consider it this way:
If you did not have header files then you would need to have the class and/or function declarations (without) definitions in every source file, this means a copy of the same declaration in every file. Thus if you modify a class you need to make the same modification in every file. By the use of a header file you have the declaration in one place and thus only one object to modify.

这篇关于C++ 头文件,代码分离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆