C++ 错误 C2664:无法将 'mw::World' 转换为 'mw::World'

C++ error C2664: Cannot convert 'mw::World' to 'mw::World'

我试图研究这个错误,但令人困惑的是某些东西如何不能转换为自身。虽然我知道为什么。

错误出现在这个函数中:

//GameObject.h

#include "BasicComponents.h"

namespace mw
{

class GameObject
{
public:
    void handleEvents(mw::World world, sf::RenderWindow& screen, mw::EventList& events) 
    {
        myInput->handleEvents(*this, screen, events);

        //Passing world here causes the error
        myPhysics->handleEvents(*this, world, screen, events);

        myGraphics->handleEvents(*this, screen, events);
    }
};

}//end of namespace

获取错误的函数是这样的:

//BasicComponents.h

namespace mw
{

//Needed for parameters
    class GameObject;
    class World;
///////////////////////

class PhysicsComponent : public mw::Component
{
public:
    virtual void handleEvents(GameObject& object, mw::World world, sf::RenderWindow& screen, mw::EventList& events) = 0;

};

}//end of namespace

我认为问题在于 BasicComponents.h 中使用的类型不完整。但是,为了让函数知道 class 存在于某处,我们需要用它来做一些事情。如果这是问题所在,我该如何解决?不然怎么会这样?

编辑:复制构造函数:

//World.h

//Copy Constructor
World(const World& me) 
{
    myMap = me.myMap;
    myObjects = me.myObjects; 
}

.

MCVE:

// Class1.h

#pragma once

#include "Class2.h"

namespace test
{

    class Class1
    {
    public:

        void function(test::Class3& c3)
        {
            myC2->function(*this, c3);
        }

        Class1() {}
        ~Class1(){}

    private:
        Class2* myC2;
    };

}//end of namespace


// Class2.h

#pragma once

namespace test
{

    class Class1;
    class Class3;

    class Class2
    {
    public:

        virtual void function(Class1 c1, Class3 c3) = 0;

        void otherFunction(){}

        Class2(){}
        ~Class2(){}

    private:

    };

}//end of namespace

您一定看到了关于 void handleEvents(mw::World world, sf::RenderWindow& screen, mw::EventList& events) 关于 mw::World 不完整的某种 warning/error。

通过按值传递class需要知道class的声明才能知道参数需要多少space。即使您可以欺骗编译器,此时 class 的大小也未知,因此将为参数保留错误数量的 space。

通过引用传递 class 没有此限制,参数所需的 space 将是已知大小,即使 class 是未定义。

如果可能传递 const mw::World& world 而不是 mw::World world,通过将其从按值传递更改为按引用传递,GameObject.h 将能够使用mw::World.

的前向声明

最后,我还建议将内联 handleEvents 移动到 BasicComponents.cpp,等到测试后再内联代码,并且只内联导致性能问题的代码。正如 Knuth 所说,"premature optimization is the root of all evil."