[英]C++ polymorphism: how to test if a class derived from another base class?
對不起標題的措辭; 我不知道如何讓它變得更好。 但我的問題的主旨是:
#include <iostream>
using namespace std;
class Base {};
class Base2 {};
class C : public Base, public Base2 {};
class D : public Base {};
void isDerivedFromBase2(Base *p) {
if (...) { /* test whether the "real object" pointed by p is derived from Base2? */
cout << "true" << endl;
}
cout << "false" << endl;
}
int main() {
Base *pc = new C;
Base *pd = new D;
isDerivedFromBase2(pc); // prints "true"
isDerivedFromBase2(pd); // prints "false"
// ... other stuff
}
如何測試由其基類指針Base *
表示的對象是否來自另一個基類Base2
?
您可以像這樣執行dynamic_cast
:
if (dynamic_cast<Base2 *>(p)) {
與使用typeid
方法不同,這個方法不需要包含額外的頭,但它也依賴於RTTI(這意味着這些類需要是多態的)。
這聽起來像一個XY問題。
對RTTI的需求(或者需要測試從哪個類派生的對象)通常是設計糟糕的標志 - 您根本不需要這樣的測試/信息。
如果層次結構設計得很好,虛函數就會扮演這些測試的角色。
要找出設計不合理的東西,問問自己“一旦掌握了信息,我將如何處理這些信息?” 答案總是那種'我會做出if / switch / ......來區別對待'; 並且正確的解決方案是以相同的方式對待它們 - 調用虛擬方法,並且每個對象攜帶正確的虛擬方法的知識,該方法知道它需要完成什么。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.