为什么在这种情况下不调用我的虚拟函数实现?
Why isn't my implementation of a virtual function being called in this case?
我可以访问一个接口,该接口实现了虚拟方法iObjectManager::getTile(const Course::ObjectId &id) = 0
。我已经在继承class ObjectManager:public Course::iObjectManager
中重新实现了该方法,如下所示:
std::shared_ptr<Course::TileBase> getTile(const Course::ObjectId &id) override;
std::shared_ptr<Course::TileBase> ObjectManager::getTile(const Course::ObjectId &id)
{
qDebug() << "Looking for tile based on ID...n";
for (unsigned i = 0; i < getMapSize(); i++) {
for (unsigned j = 0; j < getMapSize(); j++) {
std::shared_ptr<BoardPiece> tile = getGameMap().at(i).at(j);
if (tile->ID == id) {
qDebug() << "Tile found.n";
return std::move(tile);
}
}
}
qDebug() << "No tile with given index...n";
return nullptr;
}
当课程端代码调用getTile
时,问题出现了:什么也没发生。不会发出对qDebug
的调用,也不会打印任何内容。为什么即使我已经正确实现了函数(我认为(也无法调用该函数(或者调用缺少实现的函数(?
函数的调用方式如下:
tile = lockObjectManager()->getTile(ID);
其中lockObjectManager
定义为
std::shared_ptr<iObjectManager> GameObject::lockObjectManager() const
{
std::shared_ptr<iObjectManager> handler = OBJECTMANAGER.lock();
Q_ASSERT(handler);
return handler;
}
编辑
我刚刚发现,我的ObjectManager
在初始化后立即被销毁。这很奇怪,因为我在构造开始时就将其设置为我MainWindow
的成员,但它也作为初始化参数提供给我的GameEventHandler
,并且gameEventHandler
也不会死亡(基于我的qDebug
(:
GOManager_ = std::make_shared<ObjectManager>(playerAges_);
GEHandler_ = std::make_shared<GameEventHandler>(GOManager_);
事件处理程序的主窗口(或两者(应该保持对象管理器的活动状态,但它们不是......这是因为我没有提供赋值运算符,如此处所述吗?
确保 OBJECTMANAGER.lock(( 返回派生的 ObjectManager 类的实例。如果它返回 iObjectManager((,它将调用其基本版本的 getTile((,而不是重载版本。
相关文章:
- C++无法定义虚拟函数 OUTER 类和头文件
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 尝试将unique_ptrs推送到向量时使用纯虚拟函数错误
- 有没有比在库中添加一个并非由所有派生类实现的新虚拟函数更好的设计实践
- 类型擦除的std::function与虚拟函数调用的开销
- 重写虚拟函数和继承
- 用纯虚拟函数兜圈子
- 为什么使用存储在虚拟方法表中的地址调用虚拟函数的函数会返回垃圾?
- 禁止子函数调用父级的抽象(或虚拟)函数
- 无法在子类中使用虚拟函数C++
- 无法在派生对象上运行虚拟函数
- 我可以调用从 main() 覆盖的虚拟函数吗?
- 在 C++ 中将函数获取和设置为虚拟函数
- 使用在堆栈上创建的对象调用虚拟函数
- 为什么在这种情况下不调用我的虚拟函数实现?
- 在C++中使虚拟函数私有化
- 模板继承类中的虚拟函数
- 为什么构造函数的虚拟函数调用有时有效,但其他调用却无效
- doxygenc++虚拟函数和实现
- 如何从派生类函数中调用虚拟函数