2013-08-07 99 views
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); 
} 
}; 

任何幫助,將不勝感激

+6

你需要包括警衛。 http://stackoverflow.com/questions/8020113/c-include-guards –

+3

他們究竟使用什麼使他們需要包括對方? –

+1

有時可以使用前向聲明將#include指令從頭文件移動到實現文件,但無論如何您需要防範 – alexbuisson

回答

3

你需要圍繞你寫的後衛所有的頭文件。 有兩種解決方案可以實現,但只有第二種解決方案才能真正適用於所有編譯器。

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

  2. 所有的編譯器都有一個預處理器。環繞的所有文本在你的頭文件與

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

的......通過爲您的文件的唯一標識更換;例如,我經常按照慣例使用:

_filenameinlowercase_h_ 
+1

實際上'#pragma once'是[由大多數常見編譯器支持](http://en.wikipedia.org/wiki/ Pragma_once#Portability),例如鏗鏘聲,g ++,intel等等。你不能依賴這個功能仍然是事實。全局名稱空間中以下劃線開頭的名稱[已保留](http://stackoverflow.com/a/228797/1056003),不應使用。 – nijansen

0

如果你已經有了一個頭文件保護,請確保你沒有包含錯誤在用同樣的頭文件。

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

#endif