C++/CLI:在 .cpp 中定义所有内容,还是在 .h 或 .cpp 中单独定义?
抛开所有美学考虑……哪种选择更好?我主要关心的是构建时间、保持代码的可读性和易于维护,当然还有它的编译性。
我见过大多数书籍都在 .cpp 文件中定义所有内容,就像 C# 一样,但是...这不会缩短构建时间吗?好吧,非托管 C++ 的基本原理很可能不适用于托管 C++/CLI,但是请考虑一种转换场景:非托管 C++ 的项目类移至 C++/CLI 项目中,并且整个怪物构建良好,并坐在那里等待一个勇敢的人(我,咳咳)将非托管类逐渐转换为托管类,当然,还有支持测试工具。
我有点离题了,但我希望您在回答时考虑我的不寻常情况(托管和非托管交互)。
Putting all aesthetic considerations aside... Which alternative is preferrable? My main concerns are build times, keeping the code readable and easy to mantain, and of course, that it compiles.
I've seen most books define everything in a .cpp file, a la C#, but... Won't that worsen build time? Ok, it might well be that unmanaged C++ rationale doesn't work with managed C++/CLI, BUT please consider a transition scenario: An unmanaged C++'s projects classes are moved into a C++/CLI project, and the whole monster builds OK, and sits there waiting for a brave guy (me, ahem) to translate the unmanaged classes to managed ones, gradually and with a backing test harness, of course.
I digressed a little, but I wanted you to consider my unusual situation (managed and unmanaged interaction) when answering.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
.h 文件是预处理器的产物。当编译器开始编译代码时,它只是一大堆代码。在 C++/CLI 中,.h 文件的使用大大减少,您不再需要它来使声明可供其他模块使用。在托管代码中,程序集中的元数据提供它们。
C++/CLI 保留了 C++ 的构建模型,它一次编译一个源代码文件,并且需要一个链接器将代码粘合在一起。如果您的一个项目的 C++/CLI 代码分布在多个源代码文件中,您可能仍然需要 .h 文件。
因此,仅在需要时才使用 .h 文件。对于本机项目来说,建议没有什么不同。
A .h file is an artifact of the pre-processor. By the time the compiler starts to compile the code, it is just all one big wad of code. The use of .h files is greatly diminished in C++/CLI, you no longer need it to make declarations available to other modules. In managed code, the metadata in an assembly provides them.
C++/CLI retains the build model of C++, it compiles one source code file at a time and needs a linker to glue the code together. You may still need .h files if you have the C++/CLI code for one project spread across multiple source code files.
So, use .h files only when you need them. Advice that's no different for native projects.