我已經得到了答案,見底部。編譯錯誤,如果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」之前缺少'{'。 –