2016-10-24 22 views
1

我想知道是否可以傳遞一個映射,其中的數據是一個指向派生類的指針?我可以將引用傳遞給數據是指向派生類的指針的映射嗎?

#include <map> 

    class B { 

    public: 

    private: 
    int x_; 
    }; 

    class D : public B { 

    public: 

    private: 
    int y_; 
    }; 

    typedef std::map<int, B*> mapB_t; 
    typedef std::map<int, D*> mapD_t; 

    void foo(mapB_t& inmap) { 
    ; 
    } 

    int main() { 
    mapB_t mapB; 
    mapD_t mapD; 

    mapB[0] = new B; 
    mapD[0] = new D; 

    foo(mapB); 
    foo(mapD); 

    return 0; 
    } 

我收到此編譯器錯誤:

q.cc:在函數 '詮釋主()': q.cc:34:錯誤:的類型的參考無效初始化從 'mapB_t &'錯誤::類型mapD_t' q.cc:22的表達在通過參數1「無效美孚(mapB_t &)」

+1

編譯器錯誤是一個很好的跡象,你不能做到這一點。 – juanchopanza

+0

我認爲解釋應該是即使多態性允許將'D'類型對象傳遞給'B&'類型引用,'mapB_t'和'mapD_t'沒有繼承關係。因此'mapB_t&'不接受'mapD_t'。 –

+4

考慮會發生什麼:'inmap [0] = new B;'會是一場災難。 – molbdnilo

回答

1

我認爲解釋應該是即使多態性允許人們通過一個D類型的對象到B&類型的參考,mapB_tmapD_t沒有繼承關係。因此mapB_t&不接受mapD_t。在您的情況下使用多態的正確方法可能是創建BD類型的許多對象,但始終將該映射定義爲mapB_t類型。 A B*類型指針可以指向BD。您需要在類B中定義至少一個virtual函數,以允許函數foo分辨B*指針指向的對象是B還是D。下面的代碼:

class B{ 
    private: 
     int x_; 
    public: 
     virtual ~B(){}  // Only for telling the identity of an object 
    }; 
    class D: public B{ 
    private: 
     int y_;   // Virtual destructor gets automatically inherited 
    }; 

然後函數foo可以告訴如果地圖上找到了一個對象是B類型或D的使用dynamic_cast。下面的代碼:

void foo(std::map<int,B*> inmap){ 
    std::map<int,B*>::iterator it=inmap.find([Something]); 
    D *pd=dynamic_cast<D*>(it->second); 
    if(pd!=nullptr){ 
     // You know it->second is pointing to an object of type D 
    } 
    else{ 
     // Just an ordinary type B 
    } 
    } 

您將有一個更好的瞭解多態的,如果你能做到這一點的問題:https://www.hackerrank.com/challenges/magic-spells

相關問題