我在上课时遇到了一点问题。 这是我的一些代码:
//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
};
检查:When can I use a forward declaration?
在下面的示例中,我使用类 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 已经在这里定义。
希望这对您有所帮助。
关于来自其他文件的c++类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9151514/