我有一个名为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:\users\aitor\documents\visual studio 2008\projects\copter\copter\application.h(19) : error C2143: syntax error : missing ';' before '*'
1>c:\users\aitor\documents\visual studio 2008\projects\copter\copter\application.h(19) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\aitor\documents\visual studio 2008\projects\copter\copter\application.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防护,周期性地包含标头也是错误的。

尝试通过尽可能使用前向声明来删除依赖项。

如果您不能使用前向声明,则说明您的设计存在缺陷。

关于c++ - 无法解决包含头文件在内的文件使用头文件防护的错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9955501/

10-11 19:29