簡體   English   中英

C ++通過具有typeid的繼承樹進行遞歸導致此指針問題

[英]C++ recursion through inheritance tree with typeid causing this pointer problems

我正在嘗試做與此非常相似的事情。 我可能會誤解一些編程的基本規則,但是對理解為什么不起作用的任何幫助將不勝感激。 我也想知道如何使這種事情發生的技巧:

為了清楚起見,我希望先調用C.RecursiveMethod()然后再調用B.RecursiveMethod(),然后再調用A.RecursiveMethod(),然后再擊中基本情況,從而展開工作。 實際上最終發生的是C.RecursiveMethod()調用C.RecursiveMethod(),而C.RecursiveMethod()一直持續到世界末日。

提前謝謝您,如果抱歉,這是我的第一篇文章。

class A 
{
    void RecursiveMethod()
    {
        if (typeid(*this) == typeid(A))
            // Base case
        else
            SUPER::RecursiveMethod()  // The problem lies here

        // Do stuff
    };
};

class B : A 
{
    typedef A SUPER;
};

class C : B
{
    typedef B SUPER;
};

A.RecursiveMethod();   // Works, base case only
C.RecursiveMethod();   // Infinite loop
                       // this pointer is always of type C

// Also tried in vain: 
//  this->SUPER::RecursiveMethod()
//  SUPER* superCast = dynamic_cast<SUPER*>(this); superCast->RecursiveMethod();

您需要為所有類的RecursiveMethod()創建重載。 正如怪異的說法,您的指針: if (typeid(*this) == typeid(A))始終指向同一類,因此無限循環

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM