C++错误 C2664:无法将"mw::世界"转换为"mw::世界"

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

本文关键字:mw 世界 转换 错误 C2664 C++      更新时间:2023-10-16

我试图研究这个错误,但令人困惑的是,某些东西不能转换为自身。 虽然我有一个关于为什么的想法。

此函数中出现错误:

//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中使用的不完整类型。 但是,为了让我让函数知道该类存在于某个地方,并且当我们知道它时,我们将对它做一些事情。 如果这是问题所在,我该如何解决? 否则,为什么会发生这种情况?

编辑:复制构造函数:

//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

您必须看到有关mw::World不完整void handleEvents(mw::World world, sf::RenderWindow& screen, mw::EventList& events)的某种警告/错误。

使用按值传递传递类需要知道类的声明,以便知道参数需要多少空间。即使你可以欺骗编译器,此时也不知道类的大小,因此将为参数保留错误的空间量。

使用按引用传递传递类没有此限制,即使未定义类,参数所需的空间也将是已知大小。

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

最后,我还建议将内联handleEvents移动到 BasicComponents.cpp,等到测试后再内联代码,并且只内联导致性能问题的内联代码。正如Knuth所说,"过早的优化是万恶之源。