如何包含两个不同的标头,其中包含两个具有相同名称的不同类?
我正在对旧的 MFC 应用程序进行一些更改。标头“stdafx.h”包括另一个定义类“CMemDC”的标头“mfcextensions.h”。在另一个标头中,我需要包含“afxtoolbar.h”,以便我可以使用“CMFCToolBar”类。问题是,“afxtoolbar.h”最终将包含定义类“CmemDC”的“memdc.h”。结果是可以理解地得到编译错误 2011。
现在我确实可以控制定义“CMemDC”的现有代码,但它在很多地方使用,所以我不想对其进行太多更改。
克服这个问题的最佳策略是什么?我猜我可以以某种方式使用命名空间,或者另一种选择是重命名我们现有的类“CMemDC”,但这更多的是避免问题而不是永久解决问题。
干杯
I'm making some changes to an old MFC application. The header "stdafx.h" includes another header "mfcextensions.h" which defines a class "CMemDC". In another header I need to include "afxtoolbar.h" so that I can use the class "CMFCToolBar". The problem is, "afxtoolbar.h" will eventually include "memdc.h" which defines a class "CmemDC". The result is that understandably get compile error 2011.
Now I do have control over our existing code which defines "CMemDC" but this is used in a lot of places so I would rather not change it too much.
What is the best strategy for over coming this? I'm guessing that I could somehow use namespaces, or the other alternative is to rename our existing class "CMemDC" but this is more avoiding the problem rather than solving it for good.
Cheers
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用命名空间是正确的途径,但您可能还想了解为什么在整个应用程序中声明 CMemDC。除非您确实需要在任何地方声明 CMemDC,否则您可能可以从 stdafx.h 中删除包含内容,而只包含在真正需要它的 cpp 文件中。
Using namespaces is the proper route but you probably also want to look at why CMemDC is declared throughout the whole app. Unless you really need your CMemDC declared everywhere you might be able to get away with removing the include from the stdafx.h and just including in the cpp files that really need it.
C++ 命名空间可能会帮助您。将至少一个 CMemDC 类放入合适的命名空间中,并在要使用每个类的地方使用它们的完全限定名称。
并在当前范围内使命名空间使用全局
您可以避免使用完全限定名称, 如果您在同一范围内使用这两个类,则这是行不通的。
C++ namespaces might help you. Put at least one of the CMemDC classes in a suitable namespace, and use their fully qualified names where you want to use each one.
You can avoid using the fully qualified names, and make the namespace usage global in the current scope with
However, this is less explicit (in terms of not being able to directly see which CMemDC are you using at one point in the code) and in case you use both classes in the same scope this won't work.
如果你有两个同名的类,你最好的选择是使用命名空间。您也可以重命名您的班级。但所有这些都已经在您的帖子中了。所以你自己已经回答了问题。没有任何魔法可以帮助您,因为您一直遇到名称冲突的常见问题,并且引入了命名空间来解决此类问题。
If you have 2 classes with the same name your best option is to use namespaces. Also you can rename your class as well. But all of that is in your post already. So you have answered question yourself. There is no magic which can help you because you have stuck with the usual problem of the name clashing and namespaces were introduced to resolve this kind of problems.