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

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

问题描述

我是C ++的新手,我有一些关于代码分离的一般性问题。我目前构建了一个小应用程序,所有在一个文件。我现在想做的是将它转换为单独的文件,使它们包含类似的代码或whatnot。我现在的真正问题是,我怎么知道如何分离的东西?代码应该分开的不可见边际是什么?

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天全站免登陆