일상 코딩
[C++/10.04] 제휴 관계, Association 본문
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
'C++ > 따배C++ 10강 객체들 사이의 관계' 카테고리의 다른 글
[C++/10.05] 의존 관계, Dependecy on, Timer, Chrono (0) | 2021.11.03 |
---|---|
[C++/10.03] Aggregation 집합 관계 (0) | 2021.11.02 |
[C++/10.02] Composition 구성 관계 (0) | 2021.10.31 |