我得到了答案,见底部。
注意:“_AFXDLL”未针对我的情况进行预定义,静态链接到 MFC。
我有这样的代码:
我的类.h
namespace MyNameSpace
{
class CMyClass : public CMyBase
{
DECLARE_DYNAMIC( CMyClass )
...
}
}
我的类.cpp
using namespace MyNameSpace;
IMPLEMENT_DYNAMIC( CMyClass , CMyBase)
来电者
CMyBase* pObject = new MyNameSpace::CMyClass();
....
pObject->IsKindOf(RUNTIME_CLASS(MyNameSpace::CMyClass))
编译时出现错误:
error C3083: 'classMyNameSpace': the symbol to the left of a '::' must be a type
error C2277: 'MyNameSpace::CMyClass::{ctor}' : cannot take address of this member function
我调查了宏 RUNTIME_CLASS,发现它最终扩展为:
#define RUNTIME_CLASS(class_name) _RUNTIME_CLASS(class_name)
#define _RUNTIME_CLASS(class_name) ((CRuntimeClass*)(&class_name::class##class_name))
(CRuntimeClass*)(&MyNameSpace::CMyClass::classMyNameSpace::CMyClass)
理想情况下,如果它可以扩展为以下代码,那么一切都很好。
(CRuntimeClass*)(&MyNameSpace::CMyClass::classCMyClass)
现在我的问题:
“我们不能在 RUNTIME_CLASS 中使用命名空间”是 Microsoft 的一个已知问题吗?
一个更实际的问题:由于某些原因(例如来自不同命名空间的类冲突),我们不能在 cpp 文件中“使用命名空间”,我们如何在 MFC 中使用运行时类型识别?
<
回答:
Microsoft 已确认此错误 here .
解决方法很聪明,我复制在这里:
Posted by BongoVR on 8/15/2006 at 2:39 AM
define YET ANOTHER MACRO and use it instead of RUNTIME_CLASS when namespace-qualified class names are to be used in the code:
#ifdef _AFXDLL
#define RUNTIME_CLASS_N(n, class_name) (n::class_name::GetThisClass())
#else
#define RUNTIME_CLASS_N(n, class_name) ((CRuntimeClass*)(&n::class_name::class##class_name))
#endif
此宏适用于两个版本(_AFXDLL 已定义和未定义)。
最佳答案
Hans Passant 的回答:
Microsoft 已在此处确认此错误。
解决方法很聪明,我复制了它here :
Posted by BongoVR on 8/15/2006 at 2:39 AM
define YET ANOTHER MACRO and use it instead of RUNTIME_CLASS when namespace-qualified class names are to be used in the code:
#ifdef _AFXDLL
#define RUNTIME_CLASS_N(n, class_name) (n::class_name::GetThisClass())
#else
#define RUNTIME_CLASS_N(n, class_name) ((CRuntimeClass*)(&n::class_name::class##class_name))
#endif
此宏适用于两个版本(_AFXDLL 已定义和未定义)。
关于c++ - 如果 MFC RUNTIME_CLASS 参数具有命名空间,则编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17825494/