我正在使用 C++ 开发一个项目,但我是 Java 本地人,并且几乎没有 C++ 经验。我遇到的错误是 Cell 和 CellRenderer 都相互包含,但我不知道如何解决这个问题,因为它们都互相使用。如果我删除#include,我会收到单元格错误,但是如果我保留它,除了单元格包含本身之外,错误就会消失。这是我的代码:
#include <string>
#include <iostream>
#include <allegro5\allegro.h>
#include "Cell.h"
#include "Renderer.h"
using namespace std;
class CellRenderer: public Renderer{
Cell * cell;
ALLEGRO_BITMAP * image;
public:
CellRenderer(Cell * c)
{
cell = c;
image = cell->getImage();
}
void render(int x, int y)
{
al_draw_tinted_scaled_bitmap(image, cell->getColor(),0,0,al_get_bitmap_width(image),al_get_bitmap_height(image),x-cell->getRadius(),y-cell->getRadius(),cell->getRadius()*2,cell->getRadius()*2,0);
}
bool doesRender(int x, int y, int wid, int ht)
{
int cellX = cell->getX();
int cellY = cell->getY();
int radius = cell->getRadius();
return cellX>x-radius&&cellX<x+wid+radius&&cellY>y-radius&&cellY<y+ht+radius;
}
}
class Cell{
public:
bool doesRender(int x, int y, int wid, int ht)
{
return renderer->doesRender(x,y,wid,ht);
}
void render(int x, int y)//renders with center at x,y
{
renderer->render(x,y);
}
};
任何帮助将不胜感激
最佳答案
您需要用防护包围您编写的所有头文件。 有 2 个解决方案可以做到这一点,但只有第二个解决方案真正适用于所有编译器。
Visual Studio 支持
#pragma Once
。将其放在标题的第一行。所有编译器都有一个预处理器。将头文件中的所有文本用
括起来#ifdef ... #define ... other include, class declaration, etc... #endif
将 ... 替换为文件的唯一标识符;例如,我经常使用以下约定:
_filenameinlowercase_h_
关于c++ - Include 语句包含自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18094584/