我有一个名为Application.h的头文件,其中包含一个名为CollisionHandler.h的头。CollisionHandler包含Application.h,因此在编译时会出现过多包含错误。为了解决这个问题,我在标头保护之间添加了CollisionHandler,如下所示:
#ifndef COLLISION_HANDLER_INCLUDED_H
#define COLLISION_HANDLER_INCLUDED_H
#include "CollisionHandler.h"
#endif
但是,当我尝试使用类型为CollisionHandler的对象(该类在CollisionHandler.h中定义,在标头保护之间)作为Application类(在Application.h中也在标头保护间定义)的成员变量时,我会对包括Application.h的每个文件重复此错误(5次左右):
1>c:usersaitordocumentsvisual studio 2008projectscoptercopterapplication.h(19) : error C2143: syntax error : missing ';' before '*'
1>c:usersaitordocumentsvisual studio 2008projectscoptercopterapplication.h(19) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:usersaitordocumentsvisual studio 2008projectscoptercopterapplication.h(19) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
第19行是我将CollisionHandler对象声明为成员变量的行。
以下是Application.h中的代码(已识别相关行):
#include "Header.h"
#include <stdio.h>
#include "GameCharter.h"
#include <vector>
#include <boost/shared_ptr.hpp>
#ifndef COLLISION_HANDLER_INCLUDED_H //Here I include
#define COLLISION_HANDLER_INCLUDED_H //the collision
#include "CollisionHandler.h" //handler header
#endif
using namespace std;
#ifndef APPLICATION_DEFINED_H
#define APPLICATION_DEFINED_H
class LimitsManager;
class ObstacleManager;
class Application
{
public:
CollisionHandler *handler; //Here I declare the CollisionHandler
ObstacleManager *obstacleManager;
LimitsManager *limitsManager;
vector<boost::shared_ptr<GameChar> > characters;
vector<int> idsToRemove;
void gameLoop();
Application();
bool idsNeedUpdate;
bool objectsNeedToRemove;
};
#endif
这是CollisionHandler的代码。h:
#include "Header.h"
#include "Application.h"
#include "GameCharter.h"
#include "LimitObstacle.h"
#ifndef COLLISION_HANDLER_H
#define COLLISION_HANDLER_H
class CollisionHandler
{
Application *app;
public:
void handleCollisions();
CollisionHandler()
{
}
CollisionHandler(Application *app);
bool collidersAreCollidingGeneral(GameChar* char1,GameChar* char2);
bool collidersAreCollidingSecondary(GameChar* char1,GameChar* char2);
};
#endif
此外,如果我在Application.h中使用class CollisionHandler;
,然后在cpp文件中包含CollisionHandler.h,则它可以使用
循环包含标头是错误的,即使使用include保护也是如此。
尽可能使用前向声明来删除依赖项。
如果不能使用正向声明,那么您的设计就是有缺陷的。
您所需要做的就是添加/写入
pragma once
在每个头文件的顶部