为什么这段代码不起作用?
std::shared_ptr<Event> e = ep->pop();
std::shared_ptr<TrackerEvent> t;
t = std::dynamic_pointer_cast<TrackerEvent>(e);
我收到以下错误:
/usr/include/c++/4.6/bits/shared_ptr.h:386: error: cannot dynamic_cast '(& __r)->std::shared_ptr<Event>::<anonymous>.std::__shared_ptr<_Tp, _Lp>::get [with _Tp = Event, __gnu_cxx::_Lock_policy _Lp = (__gnu_cxx::_Lock_policy)2u]()' (of type 'class Event*') to type 'class TrackerEvent*' (source type is not polymorphic)
TrackerEvent
继承自 Event
所以我想问题是我不能朝这个方向转换。但是 ep->pop()
可能返回类型为 Event
或 TrackerEvent
的对象。我希望当我尝试将它转换为 TrackerEvent
并返回 NULL
时,我会知道我是否有 Event
或 跟踪器事件
...
我该怎么做?
最佳答案
编译器会在消息末尾告诉您发生了什么:
(source type is not polymorphic)
您的Event
基类需要至少有一个virtual
成员函数(即多态类型)以允许动态转换.您可以将 Event
的析构函数设为虚拟:
class Event
{
public:
virtual ~Event() { /* whatever goes here, or nothing... */ }
// ...
};
这是一个live example with polymorphic types ,显示代码编译(删除虚拟析构函数会导致编译错误 similar to the one you are seeing)。
正如 Luc Danton 所正确提及的那样在评论中,虚拟析构函数的默认版本可以这样定义(如果你的编译器在这方面是 C++11 兼容的):
class Event
{
public:
virtual ~Event() = default;
// ...
};
关于c++ - 使用 dynamic_pointer_cast 时无法动态转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16374671/