MFC在D中的CRuntimeClass替代品

时间:2012-03-09 08:11:24

标签: c++ mfc d

StackOverflow的。我在这里的第一篇文章 我从C ++和MFC来到D,我在工作中使用它 - 不仅是GUI的东西,还有许多MFC的宏(DECLARE_DYNCREATE等)和CObject类。
我怎么看,在D中我们std.Object类有factory方法。

那么,如何正确在D中重写这个C ++代码?如果有可能,当然。

class CPerson : public CObject 
{
    DECLARE_DYNAMIC( CPerson )
    // other declarations
};
IMPLEMENT_DYNAMIC( CPerson, CObject )
void DoSmthWithObject(const CObject* pObj)
{
    CPerson* pPerson = dynamic_cast<CPerson*>(pObj);
    ASSERT_VALID(pPerson);
    // Work with out CPerson object.
}

// Somethere in code create our CObject...
CObject* pMyObject = new CPerson;

// .. and do some strange things with it.
DoSmthWithObject(pMyObject);

1 个答案:

答案 0 :(得分:2)

Downcast已经在D中进行了运行时检查。尝试执行无效的向下转换将导致空引用。

class A { }
class B : A { }
class C { }

unittest
{
    A a = new A();
    Object o = a;               // upcasts are implicit
    assert(o !is null);         // OK, all classes implicitly descend from Object
    assert(cast(A)o !is null);  // OK, same class
    assert(cast(B)o is null);   // Not allowed, B is subclass of A
    assert(cast(B)a is null);   // Ditto
    assert(cast(C)o is null);   // Not allowed, C is unrelated to A
    assert(cast(C)a is null);   // Ditto
    assert(cast(C)cast(void*)a !is null); // Use intermediate cast to
                                          // void* to bypass runtime checks
}