Boost::polymorpic_downcast错误,示例为
Boost::polymorphic_downcast Error with example
昨天我开始阅读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 [...] boostcast.hpp line 97
文档
您不仅复制了示例代码。你替换了评论:
// ... 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)
并且由于CCD_ 1没有指向具有动态类型CCD_。
如果你用能产生香蕉的东西来代替这条线:
Fruit * fruit = new Banana;
那么断言(和强制转换)应该成功,为Banana提供一个正确键入的指针。
相关文章:
- 没有找到相关文章