250x250
Notice
Recent Posts
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
관리 메뉴

일상 코딩

[C++/10.04] 제휴 관계, Association 본문

C++/따배C++ 10강 객체들 사이의 관계

[C++/10.04] 제휴 관계, Association

polarcompass 2021. 11. 3. 22:23
728x90
#include <iostream>
#include <string>
#include <vector>

using namespace std;

class Doctor; // forward declaration

class Patient
{
private:
    string m_name;
    vector<Doctor *> m_doctors;

public:
    Patient(string name_in)
        : m_name(name_in)
    {
    }

    void addDoctor(Doctor *new_doctor)
    {
        m_doctors.push_back(new_doctor);
    }

    void meetDoctors();

    friend class Doctor;
};

class Doctor
{
private:
    string m_name;
    vector<Patient *> m_patients;

public:
    Doctor(string name_in)
        : m_name(name_in)
    {
    }

    void addPatient(Patient *new_patient)
    {
        m_patients.push_back(new_patient);
    }

    void meetPatients()
    {
        for (auto &elem : m_patients)
        {
            cout << "Meet Patient : " << elem->m_name << endl;
        }
    }

    friend class Patient;
};

// 전방 선언된 Doctor 요소인 m_name은 컴파일러가 어디에 있는지
// 알길이 없어서 Body 부분을 떼서 Doctor 밑에 붙여주고
// Patient class 내에는 선언부만 남겨둔다.
void Patient::meetDoctors()
{
    for (auto &elem : m_doctors)
    {
        cout << "Meet doctor : " << elem->m_name << endl;
    }
}

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);

    p3->addDoctor(d1);
    d1->addPatient(p3);

    //patients meet doctors
    p1->meetDoctors();
    // doctors meet patients
    d1->meetPatients();

    //deletes
    delete p1;
    delete p2;
    delete p3;

    delete d1;
    delete d2;

    return 0;
}
728x90