我的问题与C++中的RTTI有关,我试图检查一个对象是否属于另一个对象的类型层次结构。 BelongsTo()方法检查这一点。 我尝试使用typeid,但它会引发错误,我不确定任何其他方式如何找到要在运行时转换为目标类型。通过检测当前'this'对象类型在C++中进行类型转换
#include <iostream>
#include <typeinfo>
class X
{
public:
// Checks if the input type belongs to the type heirarchy of input object type
bool BelongsTo(X* p_a)
{
// I'm trying to check if the current (this) type belongs to the same type
// hierarchy as the input type
return dynamic_cast<typeid(*p_a)*>(this) != NULL; // error C2059: syntax error 'typeid'
}
};
class A : public X
{
};
class B : public A
{
};
class C : public A
{
};
int main()
{
X* a = new A();
X* b = new B();
X* c = new C();
bool test1 = b->BelongsTo(a); // should return true
bool test2 = b->BelongsTo(c); // should return false
bool test3 = c->BelongsTo(a); // should return true
}
制作方法虚拟,让派生类做这似乎是一个好主意,因为我有同类型层次结构中的很多类。 还是有人知道任何其他/更好的方式来做同样的事情吗?请建议。 (a)应检测输入对象类型(a)是否是类型层次结构中当前对象(b)的祖先。
虽然我不确定这可以b如果做得好,我也不知道这*如何可能会有用。出于好奇,你为什么想要实现这一目标? – ereOn 2010-06-02 11:29:57
有关示例,请参阅Neil答案的评论。 – Elroy 2010-06-02 11:33:39
例如。 C派生自B派生自A,X派生自A.在某些情况下,我可能需要验证基类指针(A *)指向的对象类型应该是类型B,而不是类型X,失败我会抛出一个错误。 – Elroy 2010-06-02 11:37:40