我已经得到了答案,见底部。编译错误,如果MFC RUNTIME_CLASS参数有命名空间
注:“_AFXDLL”不预先设定为我的情况下,静态链接到MFC。
我有这样的代码:
MyClass.h
namespace MyNameSpace
{
class CMyClass : public CMyBase
{
DECLARE_DYNAMIC(CMyClass)
...
}
}
MyClass.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我们不能使用命名空间”?
一个更现实的问题:由于某种原因(例如来自不同的命名空间冲突类),我们不能“使用命名空间”中的cpp文件,我们如何使用运行时类型识别的MFC?
回答从汉斯帕桑特:
微软已经确认了这个bug 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定义,而不是定义)。
'CMyClass'实际在'MyNamespace'中吗?如果是这样,为什么不在代码中显示呢? – juanchopanza
@ juanchopanza是的,它是。修改代码 – milesma
可能不是原因,但在MyClass.h中没有在“命名空间MyNameSpace”之前缺少'{'。 –