昨天我开始阅读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 97Documentation
发布于 2014-10-25 21:55:56
您不仅仅是复制了示例代码。您替换了下面的注释:
// ... 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;那么断言(和强制转换)应该会成功,并给出一个指向该Banana的正确类型的指针。
https://stackoverflow.com/questions/26563031
复制相似问题