昨天我开始阅读 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
最佳答案
您不只是复制示例代码。您替换了以下评论:
// ... 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 的正确类型的指针。
关于c++ - Boost::polymorphic_downcast 示例错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26563031/