【发布时间】:2019-11-03 10:14:37
【问题描述】:
我正在尝试将组件模式与模板一起使用:
template <typename ComponentGraphics>
struct Object {
ComponentGraphics* graphics;
// there is other components as well
Object(ComponentGraphics* _graphics) : graphics(_graphics) {};
void update() {
graphics->update(this); //Error occure there
};
};
然后我用一个 Player 类继承它:
class Player : public Object<PlayerGraphics> {
using Object::Object;
public:
sf::Vector2f position;
};
使用 PlayerGraphics.h:
class Player;
class PlayerGraphics{
public:
void update(Player* parent);
};
PlayerGraphics.cpp:
#include "Player.h"
void PlayerGraphics::update(Player* parent) {
// Process inputs and update parent
}
实际问题: 然后我从 PlayerGraphics 调用 update(Player * parent) 方法我得到错误 can't convert from 'Object *' to 'Player * '
对我来说,问题来自于继承,虽然我找不到我做错了什么。
【问题讨论】:
-
仔细查看错误消息并查看错误发生的确切位置(文件 + 行号)可能会有所帮助。是在
void update() { graphics->update(this); };吗? -
是的,在 PlayerGraphics.cpp 生成期间,graphics->update(this); 处触发错误。
-
一个可以剪切并粘贴到Compiler Explorer 或类似内容中的最小示例会很有帮助。
-
试试这个:static_cast
(this)->update(this)
标签: c++ templates inheritance components