堆栈溢出。我的第一篇文章在这里。
我从工作中使用的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);
最佳答案
向下转换已在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
}
关于c++ - D中的MFC的CRuntimeClass替代,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9630798/