开发者

How do I include two different headers that contain two different classes that have the same name?

开发者 https://www.devze.com 2023-02-28 01:34 出处:网络
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 \"afxtoolb

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


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++ 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

using namespace yournamespacename;

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号