簡體   English   中英

C ++多繼承多態

[英]C++ multiple inheritance polymorphism

我有幾個這樣布置的課:

class Shape { 
public:
    virtual void render() const = 0;
    ...other junk...
}
class Animation{
public:
    virtual void animate() = 0;
}

class SomeAnimatedShape : public Shape, public Animation{
    void render() { cout << "render called\n"; }
    void animate() { cout << "animate called\n"; }
}

std::vector<Shape*> shapes

問題是,我想在其基類也實現了Animation的shapes的所有Shape*上調用animate。 我嘗試這樣做:

std::vector<Shape*>::iterator it = shapes.begin();
while(it != shapes.end())
{
    Animation * a = (Animation *)(*it);
    if (a)
    {
        //a actually isn't nullptr
        a->animate();
    }
    (*it)->render();
    it++;
}

但是即使它可以編譯並正常運行並且render()被正確調用,但animate()卻從未被調用。 這段代碼有什么問題。

我也嘗試使用a = dynamic_cast<Animation*>(*it) ,但這只返回null。

您發布的代碼具有未定義的行為,因為您使用的C樣式強制轉換將始終“成功”,如果您的Shape實際上不是動畫,則不會獲得空指針。 無法確定隨后會發生什么,但是分段錯誤是一個可能的選擇。

使用dynamic_cast<Animation*>(*it) 然后,您編寫的代碼看起來不錯。 如果*it不是Animation對象,則它將返回nullptr,這是正常的。

也許您的列表中沒有任何Animation對象...

問題是,我想在其基類也實現了Animation的形狀中的所有Shape *上調用animate。 我嘗試這樣做:

根據您的代碼,Shape沒有基類。 例如,不可能有這樣的代碼:

 shapes.push_back(new Animation());

這將提示編譯錯誤。

您最有可能擁有:

shapes.push_back(new Shape());

如果要進行運行時檢查,則需要使用:

Animation * a = dynamic_cast<Animation *>(*it);

您的ShapeAnimation沒有任何關系。 您應該在SomeAnimatedShape (如果需要,然后在Animation )中投射Shape

std::vector<Shape*>::iterator it = shapes.begin();
while(it != shapes.end())
{
   SomeAnimatedShape* a = dynamic_cast<SomeAnimatedShape*>(*it);
   // Animation* a = dynamic_cast<SomeAnimatedShape*>(*it); *Both should work*

   if (a)
      a->animate();

   (*it)->render();
   it++;
}

暫無
暫無

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

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