Circular Dependency in C++

后端 未结 5 965
花落未央
花落未央 2020-12-03 01:37

The facts:

  • I have two predominant classes: Manager and Specialist.
  • There are several different types of Specialists.
  • Specialists often req
5条回答
  •  孤城傲影
    2020-12-03 02:25

    In both cases, forward declare the other class:

    Manager.h

    class Specialist;
    
    class Manager
    {
        std::list m_specialists;
    };
    

    Specialist.h

    class Manager;
    
    class Specialist
    {
        Manager* m_myManager;
    };
    

    The only time you need to bring in the header file for a class is when you need to use a member function or variable within that class, or need to use the class as a value type etc. When you only need a pointer or reference to a class, a forward declaration will suffice.

    Note that forward declarations aren't just for solving circular dependencies. You should use forward declarations wherever possible. They are always preferable to including an extra header file if it is at all viable.

提交回复
热议问题