【问题标题】:C++ cyclic inclusion issue [duplicate]C ++循环包含问题[重复]
【发布时间】:2011-06-08 18:50:30
【问题描述】:

我有这个文件 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 中)。

嗯……不知道怎么面对这个?我尝试了一切,我到处提出声明,但是,当然,它们没有任何帮助。 这个怎么解决??? (我想最好的做法是存在的,我希望这样更好:))。

谢谢。

【问题讨论】:

标签: c++ include header-files include-guards cyclic-reference


【解决方案1】:

摆脱logger.hpp 中的#include "event.hpp" - 如果您只需要在函数原型中引用Event 对象,class 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

【讨论】:

    【解决方案2】:

    转发声明时,请勿输入#include。这样做

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

    没有#include "event.hpp"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-22
      • 2010-12-11
      • 2013-07-25
      • 2013-09-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多