2011-01-13 80 views
3

我有這個文件logger.hpp:C++循環包容問題

#ifndef _LOGGER_HPP_ 
#define _LOGGER_HPP_ 

#include "event.hpp" 

// Class definitions 
class Logger { 
public: 
    /*! 
    * Constructor 
    */ 
    Logger(); 
    /*! 
    * Destructor 
    */ 
    ~Logger(); 
    /*! 
    * My operator 
    */ 
    Logger& operator<<(const Event& e); 
private: 
    ... 
}; 

#endif 

而這個文件event.hpp

#ifndef _EVENT_HPP_ 
#define _EVENT_HPP_ 

#include <string> 

#include "logger.hpp" 

// Class definitions 
class Event { 
public: 
    /*! 
    * Constructor 
    */ 
    Event(); 
    /*! 
    * Destructor 
    */ 
    ~Event(); 

    /* Friendship */ 
    friend Logger& Logger::operator<<(const Event& e); 
}; 

#endif 

嘛。在logger.hpp中,我包含event.hpp,並在event.hpp中包含logger.hpp。

  • 我需要包含event.hpp,因爲在logger.hpp中我需要定義運算符。

  • 我需要包含logger.hpp,因爲在event.hpp中,要在類Event中定義友誼。

嗯,這是,當然,一個循環遞歸

我嘗試這樣做:

1)在logger.hpp:

#ifndef _LOGGER_HPP_ 
#define _LOGGER_HPP_ 

#include "event.hpp" 

class Event; // Forward decl 

// Class definitions 
... 

不工作。編譯器告訴我,在event.hpp有一個叫做記錄器不識別的類型(他是正確的路線):

ISO C++禁止的 「記錄儀」的聲明無類型

編譯向我表明在哪裏有友誼聲明的行(在event.hpp中)。

2)在event.hpp:

#ifndef _EVENT_HPP_ 
#define _EVENT_HPP_ 

#include <string> 

#include "logger.hpp" 

class Logger; // Forward decl 

// Class definitions 
... 

不工作。編譯器告訴我,在logger.hpp有一個叫事件不識別的類型(同樣,這是正確的原因很明顯):

ISO C++禁止的「事件」 聲明無類型

編譯器向我顯示有運算符聲明的行(在logger.hpp中)。

那麼......不知道如何面對這個?我嘗試了一切,我在各處都提出了聲明,但是,當然,他們沒有任何幫助。 如何解決這個??? (我認爲存在一個最佳實踐,我希望更好:))。

謝謝。

+3

你的頭文件保護標識符不好啦使用,改變他們。 http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier – GManNickG

回答

11

擺脫#include "event.hpp"logger.hpp的 - 的class Event向前聲明應該是不夠的,如果你需要的是一個Event對象的引用的函數原型:

#ifndef _LOGGER_HPP_ 
#define _LOGGER_HPP_ 

// #include "event.hpp" // <<-- get rid of this line 

class Event; // Forward decl 

// Class definitions 
... 

class Loggerlogger.cpp的逐步落實可能需要包括event.hpp

3

當您轉發聲明時,請勿放入#include。做到像

class Event; 
class Logger { 
public: 
    /*! 
    * Constructor 
    */ 
    Logger(); 
    /*! 
    * Destructor 
    */ 
    ~Logger(); 
    /*! 
    * My operator 
    */ 
    Logger& operator<<(const Event& e); 
private: 
    ... 
}; 

沒有#include "event.hpp"