Boost :: polymorphic_downcast示例错误

时间:2014-10-25 13:41:46

标签: c++ boost

昨天我开始阅读boost文档,我复制了示例代码,程序返回错误,怎么回事?

我的代码:

#include <iostream>
#include <boost/cast.hpp>


using namespace std;

class Fruit { public: virtual ~Fruit(){}; };
class Banana : public Fruit { };

int main()
{
    Fruit * fruit = new Fruit();
    Banana * banana = boost::polymorphic_downcast<Banana*>(fruit);
    system("pause");
    return 0;
}

错误:

Assertion failed: dynamic_cast<target>(x) = x, file [...] boost\cast.hpp line 97

Documentation

1 个答案:

答案 0 :(得分:0)

您并不只是复制示例代码。你取代了评论说:

// ... logic which leads us to believe it is a Banana

有些东西并不能让我们相信:

Fruit * fruit = new Fruit();

预期断言,从您链接到的文档:

template <class Derived, class Base>
inline Derived polymorphic_downcast(Base* x);
// Effects: assert( dynamic_cast<Derived>(x) == x );
// Returns: static_cast<Derived>(x)

并失败,因为fruit未指向动态类型为Banana的对象。

如果你要用创造香蕉的东西替换那条线:

Fruit * fruit = new Banana;

然后断言(和强制转换)应该成功,给出一个正确键入指向香蕉的指针。