# person.h
#ifndef PERSON_H
#define PERSON_H
#include <iostream>
#include <string>
using namespace std;
// Person 클래스의 정의
class Person
{
private:
string name;
public:
Person(string nme);
~Person();
void print() const;
};
#endif
# student.h
#ifndef STUDENT_H
#define STUDENT_H
#include "person.h"
// Student 클래스의 정의
class Student : public Person
{
private:
string name;
double gpa;
public:
Student(string name, double gpa);
~Student();
void print() const;
};
#endif
# employee.h
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
#include "person.h"
// Employee 클래스의 정의
class Employee : public Person
{
private:
string name;
double salary;
public:
Employee(string name, double salary);
~Employee();
void print() const;
};
#endif
# person.cpp
#include "person.h"
// Person 클래스의 생성자
Person::Person(string nm)
:name(nm)
{
}
// Person 클래스의 소멸자
Person::~Person()
{
}
// print 멤버 함수의 정의
void Person::print() const
{
cout << "이름: " << name << endl;
}
# student.cpp
#include "student.h"
// Student 클래스의 생성자
Student::Student(string nm, double gp)
:Person(nm), gpa(gp)
{
}
// Student 클래스의 소멸자
Student::~Student()
{
}
// print 멤버 함수의 정의
void Student::print() const
{
Person::print(); // 오버라이드
cout << "GPA: " << gpa << endl;
}
# employee.cpp
#include "employee.h"
// Employee 클래스의 생성자
Employee::Employee(string nm, double sa)
:Person(nm), salary(sa)
{
}
// Employee 클래스의 소멸자
Employee::~Employee()
{
}
// print 멤버 함수의 정의
void Employee::print() const
{
Person::print(); // 오버라이드
cout << "급여: " << salary << endl;
}
# app.cpp
#include "student.h"
#include "employee.h"
int main()
{
// Person 클래스 인스턴스화하고 사용
cout << "Person: " << endl;
Person person("John");
person.print(); // 이름: John
cout << endl;
// Student 클래스 인스턴스화하고 사용
cout << "Student: " << endl;
Student student("Mary", 3.9);
student.print(); // 이름: Mary GPA: 3.9
cout << endl;
// Employee 클래스 인스턴스화하고 사용
cout << "Employee: " << endl;
Employee employee("Juan", 78000.00);
employee.print(); // 이름: Juan 급여: 78000
cout << endl;
return 0;
}
'언어 공부 > C++' 카테고리의 다른 글
클래스 간의 관계: 의존 (0) | 2022.06.26 |
---|---|
클래스 간의 관계: 연관 (0) | 2022.06.26 |
클래스 간의 관계: 상속 - 2(person-student) (0) | 2022.06.23 |
클래스 간의 관계: 상속 - 1 (0) | 2022.06.22 |
string-3 (0) | 2022.06.22 |
댓글