[C++] 상호참조를 할만한 두 구조체를 만들고 선언부와 구현부를 분리해보자

2022. 6. 16. 17:07코딩 1막 <C++개념편>/코딩 1막 <C++응용편>

728x90

#include <iostream>
#include <string>

using namespace std;

// 구조체 선언부
struct Teacher;
struct Student;

// 구조체 정의부
struct Teacher
{
	string name;
	int id;
	string subject;

	// Teacher 함수 선언부
	Teacher();
	Teacher(string _name, int _id, string _subject);
	void Teach();
	void ShowInfo();
};

struct Student
{
	string name;
	int id;
	int achievement;

	// Student 함수 선언부
	Student();
	Student(string _name, int _id, int _achievement);
	void Study(int point);
	void ShowInfo();
};


void main()
{
	Teacher teacherA("선생A", 1, "프로그래밍언어");
	Student studentA("학생A", 1, 0);

	teacherA.ShowInfo();
	studentA.ShowInfo();
	teacherA.Teach();
	studentA.Study(10);
	
}

// Teacher 함수의 구현부
Teacher::Teacher()
{

}
Teacher::Teacher(string _name, int _id, string _subject)
{
	name = _name;
	id = _id;
	subject = _subject;
}
void Teacher::Teach()
{
	cout << name << "가 "<< subject << " 수업을 합니다" << endl;
}
void Teacher::ShowInfo()
{
	cout << "선생의 이름 : " << name << endl;
	cout << "교번 : " << id << endl;
	cout << "------------------" << endl;
}

// Student 함수의 구현부
Student::Student()
{

}
Student::Student(string _name, int _id, int _achievement)
{
	name = _name;
	id = _id;
	achievement = _achievement;
}
void Student::Study(int point)
{
	cout << name << "가 공부를 합니다" << endl;
	achievement += point;
	cout << name << "의 학업성취도는 " << achievement << "가 되었습니다" << endl;
}
void Student::ShowInfo()
{
	cout << "학생의 이름 : " << name << endl;
	cout << "학번 : " << id << endl;
	cout << "------------------" << endl;
}

출력 결과

 

728x90