C++(따라하며 배우는 C++)

Chapter 10 -4. 제휴 관계(Association relation)

void_melody 2021. 10. 31. 18:30

Patient 클래스는 Doctor의 클래스를 순서상 알지 못한다.

그렇기에 전방 선언을 해줌으로써, Doctor 클래스가 있음을 알려주긴 했다.

하지만 그럼에도, Doctor 클래스 안의 멤버나 메소드들은 알지 못하기에, 

27번 줄에서 오류가 난다. Doctor들의 m_name이 있는지 모르기 때문.

그렇다면 해결책은 ? 

Doctor클래스가 필요한 함수를 Doctor 클래스 선언 이후에 놓는 것이다.

그러면 그제서야 아 Doctor클래스에 저런 것들이 있지 하면서 활용할 수 있겠지.

물론 기존에는 프로토타입만 선언해놓고.(void meetDoctors();)

#include <iostream>
#include <vector>
#include <string>
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()
	{
		for (auto& element : m_doctors)
			cout << "Meet doctor : " << element->m_name << endl;	// 47번줄 friend선언으로 인해.
	}
	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& element : m_patients)
			cout << "Meet patient : " << element->m_name << endl;	// 29번줄 friend선언으로 인해.
	}

	friend class Patient;
};

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

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

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


	// deletes	
	delete p1; delete p2; delete p3;
	delete d1; delete d2;
}

제휴 관계라는 것은 결국엔, 서로 사용하는 관계이고, (use)

양방향 또는 단방향 둘 다 가능할 것이다.

다만 제휴관계가 저렇게 전방선언도 해야하고, 뒤에 빼야하는 문제 등도 있어서 좀 복잡하다 보니

앞서 말한 두 관계보다는 적게 쓰인다.