클래스 간 상속 구현
이 단계에서는 C++ 의 상속 (inheritance) 에 대해 배우게 됩니다. 상속은 객체 지향 프로그래밍의 기본 개념으로, 기존 클래스를 기반으로 새로운 클래스를 생성할 수 있게 해줍니다.
WebIDE 에서 student.cpp 파일을 열고 코드를 수정하여 상속을 시연합니다.
#include <iostream>
#include <string>
// Base class
class Person {
protected:
std::string name;
int age;
public:
// Constructor
Person(std::string personName, int personAge) {
name = personName;
age = personAge;
}
// Method to display basic information
void displayInfo() {
std::cout << "Name: " << name << std::endl;
std::cout << "Age: " << age << std::endl;
}
};
// Derived class: Student inherits from Person
class Student : public Person {
private:
double gpa;
std::string major;
public:
// Constructor that calls base class constructor
Student(std::string studentName, int studentAge, double studentGPA, std::string studentMajor)
: Person(studentName, studentAge) {
gpa = studentGPA;
major = studentMajor;
}
// Additional method specific to Student
void displayStudentInfo() {
// Calling base class method
displayInfo();
std::cout << "GPA: " << gpa << std::endl;
std::cout << "Major: " << major << std::endl;
}
};
// Another derived class: Employee inherits from Person
class Employee : public Person {
private:
std::string company;
double salary;
public:
// Constructor that calls base class constructor
Employee(std::string employeeName, int employeeAge, std::string employeeCompany, double employeeSalary)
: Person(employeeName, employeeAge) {
company = employeeCompany;
salary = employeeSalary;
}
// Additional method specific to Employee
void displayEmployeeInfo() {
// Calling base class method
displayInfo();
std::cout << "Company: " << company << std::endl;
std::cout << "Salary: $" << salary << std::endl;
}
};
int main() {
// Creating objects of derived classes
Student student("Alice Johnson", 20, 3.75, "Computer Science");
std::cout << "Student Information:" << std::endl;
student.displayStudentInfo();
std::cout << "\n";
Employee employee("Bob Smith", 35, "Tech Corp", 75000.0);
std::cout << "Employee Information:" << std::endl;
employee.displayEmployeeInfo();
return 0;
}
프로그램을 컴파일하고 실행합니다.
g++ student.cpp -o student
./student
예시 출력:
Student Information:
Name: Alice Johnson
Age: 20
GPA: 3.75
Major: Computer Science
Employee Information:
Name: Bob Smith
Age: 35
Company: Tech Corp
Salary: $75000
상속에 대한 주요 사항:
- 기본 클래스 (Person) 는 공통 속성을 포함합니다.
- 파생 클래스 (Student, Employee) 는 기본 클래스에서 상속받습니다.
- 상속을 위해
: public BaseClassName을 사용합니다.
- 파생 클래스에서 새로운 속성과 메서드를 추가할 수 있습니다.
- 파생 클래스에서 기본 클래스 메서드를 사용할 수 있습니다.