我的問題與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