c++ - Boost::polymorphic_downcast 示例错误

标签 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

最佳答案

您不只是复制示例代码。您替换了以下评论:

// ... 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/

相关文章:

c++ - 在 C++ 中从十六进制转换为 unsigned int*

boost - boost::program_options 中的default_value 和implicit_value 有什么区别?

c++ - 在不使用动态数组的情况下进行数组初始化时出现问题

c++ - g++ 链接器问题

c++ - 在编译时检查 tr1 数组的大小

c++ - 使用捆绑属性时 BGL 中的不完整类型错误

c++ - 我如何更改 shm_open 路径?

c++ - 在构造函数之后初始化 boost::asio 套接字

c++ - 如何让编译器警告这是一个无效的 boolean 值?

c++ - 不包括 boost 信号调用