C++头文件约定
我正在使用 C++ 开发一个小游戏,并且使用了 Eclipse CDT 的类生成器。它创建了一个包含类定义的 .h 文件和一个包含所述类的无正文方法的 .cpp 文件。
因此,如果我遵循模板,我将拥有一个充满方法声明的 .cpp 文件和一个包含方法主体的 .cpp 文件。但是,我无法将 .cpp 文件包含在另一个文件中。
那么 C++ 中类和包含文件的约定是什么?我所做的就是在 .h 文件中的类声明下方填写方法体,并删除 .cpp 文件。
I am working on a small game using C++, and I used Eclipse CDT's class generator. It created a .h file with the class definitions and a .cpp file that included body-less methods for said class.
So if I followed the template, I'd have a .cpp file filled with the methods declarations, and a .cpp file with method bodies. However, I can't include a .cpp file within another.
So what is the convention in C++ with classes and include files? What I did was fill in the method bodies right under the class declaration in the .h file, and deleted the .cpp file.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不必包含 .cpp 文件。只需包含 .h 文件即可。 .h 表示标头,即它应该具有的只是函数/对象定义。实际的实现位于同名的 .cpp 文件中。链接器将为您处理理顺它。
头文件包含声明(也称为原型)。包含标头可以让程序知道“我声明一些看起来像这样的东西存在”。
标头的用户节省了我们在代码文件中到处声明方法的精力 - 我们只需执行一次,然后导入文件。
.c/.cpp/.cc 文件包含定义 - 它告诉程序该函数的作用。
您不必“包含”.c 文件,因为编译器就是这样做的 - 它将所有 .c 文件编译为机器代码。
You don't have to include the .cpp file. Including the .h file is all it takes. .h means header, ie, all it should have is function / object definitions. The actual implementations go in the .cpp file of the same name. The linker will deal with straightening it out for you.
The header file contains declarations (also known as prototype). Inclusion of the header lets the program know "I declare something that looks like this exists".
The user of headers saves us the effort of declaring methods all over the place in our code files - we just do it once, then import the file.
The .c/.cpp/.cc file includes the definition - which tells the program what the function does.
You do not have to "include" .c files because that's what the compiler does - it compiles all your .c files into machine code.
您还可以做的另一件事是在创建头文件时使用预处理器指令
ifdef 和 endif。这将防止您的头文件被多次包含。
这是我在创建新头文件时使用的标准做法。
One more thing you can do is while creating a header file is to use the preprocessor directive
ifdef and endif. This will prevent your header file being included multiple times.
This is a standard practice which I use whenever I create a new header file.
我不太确定我是否理解。头文件定义了该类的含义和功能,并将其包含到需要使用该类的任何源文件中。
源文件实现了该类如何执行其操作。
但是,您可以将
.cpp
包含到另一个.cpp
中(您可以将任何内容包含到任何内容中),但您不需要这样做。I'm not quite sure I understand. The header files defines what the class is and can do, and you include that into any source files that need to use the class.
The source file implements how the class does its action.
However, you can include a
.cpp
into another (you can include anything into anything), but you don't need to.