gpt4 book ai didi

C++多重继承多态

转载 作者:行者123 更新时间:2023-11-27 23:00:22 24 4
gpt4 key购买 nike

我有几个类是这样布局的:

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 .

问题是,我想在所有 Shape* 上调用动画在 shapes其基类也实现了动画。我试过这样做:

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。

最佳答案

您发布的代码具有未定义的行为,因为如果您的 Shape 实际上不是动画,那么您使用的 C 风格转换将始终“成功”,因为您不会获得空指针。无法判断之后会发生什么,但段错误是一个可能的选择。

使用 dynamic_cast<Animation*>(*it) !然后你写的代码看起来不错。如果*it不是 Animation object 那么它会返回一个 nullptr,这是正常的。

也许你没有Animation列表中的对象 ...

关于C++多重继承多态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28343954/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com