C++/Class 2021. 3. 19. 19:40

연계, 제휴 관계 (Association)

  • 의사 클래스와 환자 클래스로 비유

    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    class Doctor;
    
    class Patient
    {
      string            name_;
      vector<Doctor*>    doctors_;
    
    public:
      Patient(const string &name_in)
        : name_{name_in}
      {}
    
      void    addDoctor(Doctor* new_doctor)
      {
        doctors_.push_back(new_doctor);
      }
    
      void    meetDoctors();
    
      friend class Doctor;
    };
    
    class Doctor
    {
      string                name_;
      vector<Patient*>    patients_;
    
    public:
      Doctor(const string &name_in)
        : name_{name_in}
      {}
    
      void    addPatient(Patient* new_patient)
      {
        patients_.push_back(new_patient);
      }
    
      void    meetPatients()
      {
        for (auto& e : patients_)
          cout << "Meet patient : " << e->name_ << '\n';
      }
    
      friend class Patient;
    };
    
    void    Patient::meetDoctors()
    {
      for (auto& e : doctors_)
        cout << "Meet doctor : " << e->name_ << '\n';
    }
    
    int        main()
    {
      Patient* p1 = new Patient("Jack Jack");
      Patient* p2 = new Patient("Dash");
      Patient* p3 = new Patient("Violet");
    
      Doctor* d1 = new Doctor("Doctor K");
      Doctor* d2 = new Doctor("Doctor L");
    
      p1->addDoctor(d1);
      d1->addPatient(p1);
    
      p2->addDoctor(d2);
      d2->addPatient(p2);
    
      p2->addDoctor(d1);
      d1->addPatient(p2);
    
      cout << "p1\n";
      p1->meetDoctors();
    
      cout << "\nd1\n";
      d1->meetPatients();
    
      delete p1, p2, p3, d1, d2;
    
    }
    
    /* stdout
    p1
    Meet doctor : Doctor K
    
    d1
    Meet patient : Jack Jack
    Meet patient : Dash
    */

'C++ > Class' 카테고리의 다른 글

C++ 상속 (Inheritance)  (0) 2021.03.19
C++ 의존 관계 (Dependency)  (0) 2021.03.19
C++ 구성 관계 (Composition Relationship)  (0) 2021.03.19
C++ 객체들의 관계 (Object Relationship)  (0) 2021.03.19
C++ Nested Types  (0) 2021.03.16