C++ 将函数实现对象作为接口(interface)类型传递

标签 c++ interface

我的界面看起来像这样:

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 左值引用。

因为pSpriteObjectSpriteObject * 类型的左值,所以没有匹配函数可以调用它,它会尝试使用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/

相关文章:

C++ 在不释放内存的情况下调用析构函数

c++ - 将前一个节点的地址存储到当前节点的 “prev”部分中

c# - 为什么在 C# 中需要提及访问修饰符来实现接口(interface)属性?

python - numpy 与 mlabwrap 的 matlab 接口(interface)

c++ - 在 Visual Studio 中构建 C++ 项目不会创建任何文件

c++ - 临时 B() 是否通过下面引用 int& ri 的初始化来延长其生命周期?

c++ - 运行时函数模板类型推导

c++ - 使用没有堆内存分配的接口(interface)的框架应用程序?

java - Dropbox Djinni - Java 接口(interface)与类扩展

Java 泛型接口(interface)转换