我的界面看起来像这样:
class GameObject
{
public:
virtual ObjType getType() = 0;
virtual void setType(ObjType ot) = 0;
protected:
ObjType objtype;
};
然后我有实现这个接口(interface)的类
class SpriteObject : public GameObject
{
public:
SpriteObject();
virtual ~SpriteObject();
ObjType getType() { return objtype; }
void setType(ObjType ot) { objtype = ot; }
private:
};
class LayerObject : public GameObject
{
public:
LayerObject ();
virtual ~LayerObject ();
ObjType getType() { return objtype; }
void setType(ObjType ot) { objtype = ot; }
private:
};
在主类中,我有一个函数,我尝试将 SpriteObject 传递给 看起来像这样:
bool HelloWorld::NodeAction(GameObject* &pGameObj)
{
}
当我尝试做的时候:
SpriteObject *pSpriteObject = new SpriteObject();
NodeAction(pSpriteObject);
我收到这个错误:
error C2664: 'bool HelloWorld::NodeAction(GameObject *&)' : cannot convert argument 1 from 'SpriteObject *' to 'GameObject *&'
最后,我想要一个全局函数,可以获取实现 GameObject 的不同对象。
最佳答案
这个函数:
bool HelloWorld::NodeAction(GameObject* &pGameObj)
需要 GameObject*
的非 cv 左值引用。
因为pSpriteObject
是SpriteObject *
类型的左值,所以没有匹配函数可以调用它,它会尝试使用implicit conversion。通过这些转换找到重载函数:
左值到右值的转换
A glvalue of any non-function, non-array type T can be implicitly converted to a prvalue of the same type. If T is a non-class type, this conversion also removes cv-qualifiers.
指针转换
A prvalue pointer to a (optionally cv-qualified) derived class type can be converted to a prvalue pointer to its (identically cv-qualified) base class.
因此,这条线
节点 Action (pSpriteObject);
期望一个具有这些原型(prototype)之一的函数:
bool HelloWorld::NodeAction(GameObject*)
bool HelloWorld::NodeAction(GameObject* const&)
bool HelloWorld::NodeAction(GameObject* &&)
一切都可以接受,但是
bool HelloWorld::NodeAction(GameObject*)
应该是首选,参见this question .对于基本类型,按值传递应该比按引用传递更快,即使是在 C++11 之前
关于C++ 将函数实现对象作为接口(interface)类型传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40815753/