gpt4 book ai didi

c++ - 如何防止连续循环 #include 语句?

转载 作者:行者123 更新时间:2023-11-30 01:29:04 26 4
gpt4 key购买 nike

我有两个类的问题,每个类都需要在它们的头文件中了解另一个类。

结构.h

#ifndef STRUCTURE_H
#define STRUCTURE_H

#include <vector>
#include "Sprite.h"
#include "Bullet.h"

class Structure: public Sprite{
public:
Structure(const BITMAP bm, const Vec2& pos, const Vec2& vel,
const RECT boundaries, std::vector<std::vector<bool>> holes);
virtual ~Structure() = 0;

void takeDamage(const Bullet* bullet);
protected:
std::vector<std::vector<bool>> mBulletHoles;
};

#endif

结构.cpp

#include "Structure.h"

Structure::Structure(const BITMAP bm, const Vec2& pos, const Vec2& vel,
const RECT boundaries, std::vector<std::vector<bool>> holes)
:Sprite(bm, pos, vel, boundaries),
mBulletHoles(holes)
{}

void Structure::takeDamage(const Bullet* bullet){

}

Sprite::~Sprite(){}

子弹.h

#ifndef BULLET_H
#define BULLET_H

#include "Animate.h"
#include "Structure.h"

class Bullet: public Sprite{
public:
Bullet(const BITMAP bm, const Vec2& pos, const Vec2& vel, const RECT boundaries,
bool friendly);
virtual ~Bullet();

int checkCollision(Animate* target);
void checkCollision(Structure* target, float dt);

private:
float mTimeSinceCollision;

bool mFriendly;
bool mActive;

const static float mPenetrationTime;
};

#endif

子弹.cpp

#include "Bullet.h"

Bullet::Bullet(const BITMAP bm, const Vec2& pos, const Vec2& vel,
const RECT boundaries, bool friendly)
:Sprite(bm, pos, vel, boundaries),
mTimeSinceCollision(0.0f),
mFriendly(friendly),
mActive(true)
{}

int Bullet::checkCollision(Animate* target){
int returnPoints = 0;
if((target->identifier() == "Player") && !mFriendly){
if(isTouching(target)){
target->takeDamage();
mActive = false;
}
}else if((target->identifier() == "Alien") && mFriendly){
if(isTouching(target)){
returnPoints = target->takeDamage();
mActive = false;
}
}
return returnPoints;
}

void Bullet::checkCollision(Structure* target, float dt){
if(isTouching(target)){
mTimeSinceCollision += dt;
target->takeDamage(this);
}
if(mTimeSinceCollision >= mPenetrationTime){
mActive = false;
}
}

Bullet::~Bullet(){}

const float Bullet::mPenetrationTime = .05;

因为两个头文件相互调用,所以我得到了很多错误。我厌倦了更换

#include "Bullet.h"

在 Structure.h 中用

class Bullet;

但是编译器说我有多重定义的类型。您应该如何绕过循环 #include 语句?

最佳答案

首先,你要避免那些循环包含。然后,如果真的没有出路,您只需在 header 中声明您需要的类即可。

例如,在 Bullet.h 中:

#include "Sprite.h"

class Structure; // Can now use Structure* and Structure&
class Bullet {
...
}

在 Bullet.cpp 中

#include "Bullet.h"
#include "Structure.h"

在 Structure.h 中:

#include "Sprite.h"

class Bullet; // Can now use Bullet* and Bullet&
class Structure {
...
}

在 Structure.cpp 中

#include "Structure.h"
#include "Bullet.h"

当编译器在 Bullet 实现中看到未知的“Sprite”对象时,他会知道您指的是特定对象,因为您在 header 中进行了声明。参见 C++ FAQ Lite例如。

关于c++ - 如何防止连续循环 #include 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6441141/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com