2

我正在使用 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);
}
};

任何帮助将不胜感激

4

2 回答 2

4

您需要用保护包围您编写的所有头文件。有两种解决方案可以做到这一点,但只有第二种真正适用于所有编译器。

  1. Visual Studio 支持#pragma once. 把它放在标题的第一行。

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

      #ifdef ...
      #define ...
    
       other include, class declaration, etc...
    
      #endif
    

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

 _filenameinlowercase_h_
于 2013-08-07T04:30:43.427 回答
1

如果您已经有一个标头保护,请确保您没有错误地在其中包含相同的头文件。

例子

#ifndef EXAMPLE_H_
#define EXAMPLE_H_
.
.
.
#include Example.h   //It should be removed
.
.

#endif
于 2013-08-07T05:04:33.623 回答