来自其他文件的c++类

c++ class from other file

本文关键字:c++ 文件 其他      更新时间:2023-10-16

我对类有点问题。这是我的一些代码:

//GameMap.h
#ifndef GAMEMAP_H
#define GAMEMAP_H
#include "apath.h"
class GameMap
{
    /*class definition here*/
};
#endif

//apath.h
#ifndef APATH_H
#define APATH_H
class path
{
    //some code...
    void DoSomething(GameMap map);
    //rest of class body
};
#endif

我不能在apath.h中使用GameMap,当我试图在这个文件中包含"GameMap.h"时,我得到了一些愚蠢的错误…我还试图在定义路径类之前添加类GameMap;。没有任何帮助…我真的需要在这里使用它。。。如果需要,我可以发布更多代码

感谢任何回复!

您应该在apath.h:中使用类GameMap的前向声明

class GameMap; // forward declaration
class path
{
    //some code...
    void DoSomething(GameMap map);
    //rest of class body
};    

支票:我什么时候可以使用远期申报?

在下面的示例中,我使用类A的前向声明,以便能够声明使用它的函数useA

// file a.h
class A;
void useA(A a);

然后在main.cpp中我有:

#include "a.h"
class A
{
public:
    void foo() { cout << "A"; }
};
void useA(A a)
{
    a.foo();
}

这是绝对正确的,因为这里已经定义了类A。

希望这能有所帮助。

您应该检查PIMPL习语。

在路径头中:

class GameMap;
class Path
{
public:
  void useMap( GameMap * map );
};

路径内来源:

#include "Path.h"
#include "GameMap.h"
void Path::useMap( GameMap * map )
{
  // Use map class
}

更多链接:链接和连接的主题。

您有一个循环包含问题。GamePath.h包括apath.h,所以尝试将GamePath.h包含在apath.h中往好了说是脆弱的,往坏了说会产生错误(您的情况)。最好的办法是找到GamePath.h使用了apath.h的哪些部分,并将它们重构到一个公共头文件中,比如common.h,并在GamePath.h和apath.h中包含common.h。这样,你就不再有循环include了,你可以绘制一个include图,作为一个漂亮的DAG。

您正在尝试执行循环包含,这显然是被禁止的。

我建议你在apath.h中转发声明GameMap,并将其作为常量引用传递:

class GameMap; // forward declaration
class path
{
    //some code...
    void DoSomething(const GameMap &map);
    //rest of class body
};

const ref比简单ref更好,因为它明确地告诉对象在函数调用期间不能更改。

在apath.h 中进行外部声明

class GameMap;

更改方法签名后:

void DoSomething(GameMap& map);

void DoSomething(GameMap* map);