C ++ cyclic inclusion issue

I have this logger.hpp file:

#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

And this event.hpp file

#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

Well. In logger.hpp I turn on event.hpp, and in event.hpp I turn on logger.hpp.

  • I need to include event.hpp because in logger.hpp I need to define a statement.

  • I need to enable logger.hpp because in event.hpp the friendship will be defined in the Event class.

Well, this, of course, is cyclic recursion .

I tried this:

1) In logger.hpp:

#ifndef _LOGGER_HPP_
#define _LOGGER_HPP_

#include "event.hpp"

class Event; // Forward decl

// Class definitions
...

Does not work. The compiler tells me that event.hpp has an unrecognized type called Logger (and it's right, of course):

ISO C ++ Prohibits Declaring 'Registrar Without Type

The compiler points me to a line (in event.hpp) where there is a declaration of friendship.

2) In event.hpp:

#ifndef _EVENT_HPP_
#define _EVENT_HPP_

#include <string>

#include "logger.hpp"

class Logger; // Forward decl

// Class definitions
...

. , logger.hpp , Event (, , ):

ISO ++ ""

( logger.hpp), .

... , ? , , , , . ??? ( , , :)).

Thankyou.

+3
2

#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 Logger logger.cpp, , event.hpp.

+11

, #include.

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

#include "event.hpp"

+3

Source: https://habr.com/ru/post/1785289/


All Articles