我有这个文件logger.hpp:
#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 中有一个未被识别的类型,称为 Logger(他当然是对的):
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 中有一个未被识别的类型,称为 Event(同样,出于显而易见的原因,它是正确的):
ISO C++ 禁止声明没有类型的“事件”
编译器向我指出存在运算符声明的行(在 logger.hpp 中)。
嗯……不知道该怎么面对?我尝试了一切,我到处提出声明,但是,当然,它们没有任何帮助。这个怎么解决???(我想存在一个最佳实践,我希望这样更好:))。
谢谢你。