来自其他文件的c++类
c++ class from other file
我对类有点问题。这是我的一些代码:
//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);
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 文本文件中的单词链表
- CMake-按正确顺序将项目与C运行时对象文件链接
- 使用新行和不使用新行读取文件
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 挂起和取消挂起一个文件DLL
- 如何确定我已使用非编码文件到达 EOF?
- 命名空间中具有.h和.cpp文件的类
- 如何使用ndk-build.cmd构建Android.so文件
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 读取文件并输入到矢量中
- 在C++中查找文件
- c++库的公共头文件中应该包含什么
- 用c++从输入文件中读取另一行
- Cppcheck生成xml转储文件
- 读取文件的最后一行并输入到链接列表时出错
- 无法编译 rtmidi 测试 cmidiin.cpp 文件, 非法指令
- 如何将内容数组写入文本文件?
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到