C++ 的头文件应该是什么样子?项目?
我学过C,现在我决定转向C++。
因此,在 C 中,我在头文件中使用了 #ifndef
#endif
。我应该在 C++ 中使用相同的命令吗?或者有一些替代方案吗?
I’ve studied C, and now I’ve decided to switch to C++.
So, in C, I used #ifndef
#endif
in my header files. Should I use the same commands in C++? Or are there some alternatives?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,预处理器(大部分)以相同的方式工作,因此您仍然应该使用预处理器指令来防止多次包含相同的代码。
C 和 C++ 预处理器之间的任何功能差异都可能是边缘情况,不太可能与您当前的学习水平相关。
Yes, the preprocessor works (mostly) the same way, so you should still use preprocessor directives to guard against including the same code more than once.
Any differences in functionality between the preprocessor in C and C++ are likely to be edge cases that are unlikely to be relevant at your current learning level.
文件/头关系在 C 和 C++ 中是相同的。
foo.h:
与 C 对应的预处理器相比,C++ 预处理器本质上是相同的。所有指令都可以使用任一语言运行,无论是编写在标头 (.h) 还是源文件(.c、.cc、.cpp)中。
在这里了解有关标头奇迹的更多信息!
The file/header relationship is identical in C and C++.
foo.h:
The C++ preprocessor is essential the same when compared to it’s C counterpart. All directives will work in either language whether written in a header (.h) or a source file (.c, .cc, .cpp).
Read more about the wonders of headers here!
Commader_Quazar 的答案是正确且足够的。
或者,您可以将: 替换
为:,
这样您可以编写 1 行代码而不是 3 行,并且更不容易出错(因为在这种情况下,您不必担心记住将
#endif
放在文件末尾)但是我个人更喜欢第一个选项。The answer from Commader_Quazar is right and enough.
ALternatively you can substitute:
with:
which lets you write 1 line of code instead of 3, and is less error prone (since in this case you don't have to worry about remembering to put
#endif
at the end of the file) however I personally prefer the first option.除了其他人解释的宏保护之外,最好有一个命名空间,然后你的类、结构和所有其他函数都进入这个命名空间。
Besides macro guard explained by others, it would be nice to have a namespace and then your classes, structs, and all other functions go inside this namespace.