为什么在这种情况下不调用我的虚拟函数实现?

Why isn't my implementation of a virtual function being called in this case?

本文关键字:虚拟 函数 实现 我的 调用 这种情况下 为什么      更新时间:2023-10-16

我可以访问一个接口,该接口实现了虚拟方法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((,而不是重载版本。