c++ - 如果 MFC RUNTIME_CLASS 参数具有命名空间,则编译器错误

标签 c++ mfc compilation

我得到了答案,见底部。

注意:“_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)

现在我的问题:

  1. “我们不能在 RUNTIME_CLASS 中使用命名空间”是 Microsoft 的一个已知问题吗?

  2. 一个更实际的问题:由于某些原因(例如来自不同命名空间的类冲突),我们不能在 cpp 文件中“使用命名空间”,我们如何在 MFC 中使用运行时类型识别?

    <
来自 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 已定义和未定义)。

最佳答案

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/

相关文章:

c++ - 从 C++ 到 C 文件中定义的变量/函数的 undefined reference

c++ - 在我的组合框中输入数据

c++ - 消除光流算法中的噪声?

c++ - 为什么STL不提供c风格列表?

C++ 开发环境 Eclipse

c# - 如何从 .NET 可执行文件中获取输出并传送到 MFC 应用程序?

c++ - 使用 MFC 编辑控件中的 block 字符(仅限 float 的示例)

编译和链接纯 C 和 CUDA 代码 [警告 : implicit declaration of function]

build-process - cmake命令语法问题

c++ - linux 上的 c++ 交叉编译到 windows