我的问题与 C++ 中的 RTTI 有关,我试图检查一个对象是否属于另一个对象的类型层次结构。 BelongsTo() 方法会检查这一点。 我尝试使用 typeid,但它会引发错误,并且我不确定是否有其他方法可以找到要在运行时转换的目标类型。
#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
}
将方法设为虚拟并让派生类执行这似乎是一个坏主意,因为我在同一类型层次结构中有很多类。 或者有人知道任何其他/更好的方法来做同样的事情吗?请提出建议。
更新:b.BelongsTo(a) 应检测输入对象类型 (a) 是否是类型层次结构中当前对象 (b) 的祖先。
最佳答案
这没有意义 - 您可以调用该函数这一事实意味着该参数属于 X 层次结构,因为这是参数的类型。动态转换旨在找出已知层次结构中的实际类型。
代码中的语法错误:
return dynamic_cast<typeid(*p_a)*>(this) != NULL;
是因为 typeid 不是类型 - 你根本不能将它用作像这样的dynamic_cast类型。
如果按照 Naveen 的建议,您想查明某个实例是否属于子层次结构,请使用:
if ( dynamic_cast <A*>( some_x_ptr ) ) {
// yes, belongs to A sub-hierarchy
}
编辑:您有:
A <- P <- X
A <- Q <- Y
然后:
A * a = new X;
dynamic_cast <P *>( a ); // not null
dynamic_cast <Q *>( a ); // null
关于c++ - 通过检测当前 'this' 对象类型在 C++ 中进行类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2956404/