RTTI ---- Imitate from Inside MFC

本文详细介绍了RTTI(运行时类型信息)机制的工作原理及其在MFC中的实现方式。通过具体的结构体CRuntimeClass定义和宏的使用,展示了如何在C++中实现对象类型的动态检查与构造。此外还提供了一种通过IsKindOf函数来判断对象继承关系的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 RTTI means Runtime Type Information.
The compiler itself enable this functionality.

Now here just to imitate the mechalism referring to Inside MFC.

1.  CRuntimeClass node to construct the link list.

struct CRuntimeClass
{
    LPCSTR                         m_lpszClassName;
    int                                     m_nObjectSize;
    UINT                                m_wSchema;
    CObject*                         (PASCAL* m_pfnCreateObject)();
    CRuntimeClass*         m_pBaseClass;
    CRuntimeClass*         m_pNextClass;

    static CRuntimeClass*   pFirstClass;
}

2.  DECLARE_DYNAMIC(class_Name) to declare in .h file.

#define DECLARE_DYNAMIC(class_name) /
public:  /
             static CRuntimeClass class##class_name;  /
             virtual CRuntimeClass* GetRuntimeClass() const;

3.  Implement macro in .cpp file

#define IMPLEMENT_DYNAMIC(class_name, base_class_name)  /
               _IMPLEMENT_RUNTIMECLASS(class_name, base_class_name, 0xFFFF, NULL)

#define _IMPLEMENT_RUNTIMECLASS(class_name, base_class_name, wSchema, pfnNew) /
               static char _lpsz##class_name[] = #class_name;
               CRuntimeClass class_name::class##class_name = { /
                _lpsz##class_name, sizeof(class_name), wShema,pfnNew, /
                RuntimeClass(base_class_name),NULL }; /
                static AFX_CLASSINIT _init_##class_name(&class_name::class##class_name); /
                CRuntimeClass* class_name::GetRuntimeClass() const /
                {return &clas_name::class##class_name; }

#define RUNTIME_CLASS(class_name)  /
                (&class_name::class##class_name)

struct AFX_CLASSINIT
          {AFX_CLASSINIT(CRuntimeClass* pNewClass); };

3.  The root class CObject has the specific definition as its m_pBaseClass = NULL.

4. Initialize the static variable.
   CRuntimeClass* CRuntimeClass::pFirstClass = NULL;

5. Initial Class to link all the nodes.
   AFX_CLASSINIT::AFX_CLASSINIT(CRuntimeClass* pNewClass)
{
       pNewClass->m_pNextClass = CRuntimeClass::pFirstClass;
       CRuntimeClass::pFirstClass = pNewClass;
}

6.  Define the judge function in CObject IsKindof()
    BOOL CObject:: IsKindOf(const CRuntimeClass* pClass) const
{
       CRuntimeClass* pClassThis = GetRuntimeClass();
      while (pClassThis != null)
    {
          if (pClassThis == pClass)
             return True;
          pClassThis = pClassThis->m_pBaseClass;
    }
     return FALSE;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值