【发布时间】:2015-12-03 06:31:25
【问题描述】:
如果我将指向派生类对象的派生类的指针静态转换为基类的指针,然后取消引用该指针并将其作为方法参数传递,为什么取消引用的指针是基类类型而不是派生的类型?它仍然指向派生类的对象,但取消引用的类型是基类?
template <typename T>
inline void AttachEvent(EventID eventId, T* eventHandler) // the second paramater is a class derived from EventHandler
{
cout << eventHandler << endl;
static_assert(std::is_base_of<EventHandler, T>::value, "Class provided is not derived from EventHandler");
EventManager* pEventManager = EventManager::GetSingletonPtr();
assert(pEventManager);
if (pEventManager)
{
pEventManager->AttachEvent(eventId, *static_cast<EventHandler*>(eventHandler));
}
}
void EventManager::AttachEvent(EventID eventId, EventHandler& eventHandler)
{
EventMapIterator result = m_eventMap.find(eventId);
assert(result != m_eventMap.end());
if (result != m_eventMap.end())
{
assert(result->second);
result->second->AttachListener(eventHandler);
}
}
【问题讨论】:
-
所以你是在问为什么演员表确实像它声称的那样做?
-
哦,所以它同时转换了指针和它指向的对象?
-
显示代码示例并解释为什么您认为其可观察到的行为违反直觉。
-
不,它绝对不会对对象做任何事情。您使用不同的指针类型,仅此而已。多态允许你调用派生类的方法。
-
好的,但是指针被取消引用,我传递的是派生类型的对象,而不是 EventHandler,但是 EventManager::AttachEvent 接受 EventHandler& 变量作为参数?
标签: c++ pointers inheritance