c++ - Include 语句包含自身

标签 c++ include

我正在使用 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 个解决方案可以做到这一点,但只有第二个解决方案真正适用于所有编译器。

  1. Visual Studio 支持#pragma Once。将其放在标题的第一行。

  2. 所有编译器都有一个预处理器。将头文件中的所有文本用

    括起来
      #ifdef ...
      #define ...
    
       other include, class declaration, etc...
    
      #endif
    

将 ... 替换为文件的唯一标识符;例如,我经常使用以下约定:

 _filenameinlowercase_h_

关于c++ - Include 语句包含自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18094584/

相关文章:

c++ - 在 Qt 中包含 OpenGL 库

c++ - 是否可以直接从用户(标准输入)接受字符串流?

c++ - 为什么省略 “#include <string>”有时只会导致编译失败?

c++ - 无法在具有不同语言设置的 PC 上设置组策略设置

c++ - 确定字符串是否为 double

c - 使用不同的宏多次包含一个文件

c++ - h和hpp问题,包含顺序错误

javascript - 由于 header 代码是从不同的文件加载的,网站会闪烁

c++ - C++ 中的有序容器与无序容器

c++ - Boost.Intrusive Containers - 不同大小的元素