Circular Dependency in C++

后端 未结 5 959
花落未央
花落未央 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条回答
  •  萌比男神i
    2020-12-03 02:16

    One option is to forward declare one of the people, as you suggest:

    struct specialist;
    
    struct manager
    {
        std::vector > subordinates_;
    };
    
    struct specialist
    {
        std::weak_ptr boss_;
    };
    

    However, if you end up having more of a tree-structure (where you have multiple layers of management, a person base class would also work:

    struct person
    {
        virtual ~person() { }
        std::weak_ptr boss_;
        std::vector > subordinates_;
    };
    

    You can then derive specific classes for different types of people in the hierarchy. Whether or not you need this depends on how exactly you intend to use the classes.

    If your implementation doesn't support std::shared_ptr, it may support std::tr1::shared_ptr or you can use boost::shared_ptr.

提交回复
热议问题