상속
class Person { // 기본 클래스 Person 선언
int age; // private 변수이므로 Person에서만 접근 가능
public:
void setAge(int age) { this->age = age; }
void show() { cout << age; }
};
class Student : public Person { // Person을 상속받는 Student 선언
double score;
public:
void setScore(double score) { this->score = score; }
void showStudent() {
cout << score << ' : ';
show(); // 파생 클래스에서 기본 클래스 멤버 호출
}
};
// Student를 상속받는 Intern 선언
class Intern : public Student { ... };
int main() {
Student mark;
Student *pDer = &mark;
Person *pBase = pDer; // 업 캐스팅
pDer->setAge(20); // mark의 age를 20으로 설정
pBase->show(); // 20 출력
pDer->setScore(4.42); // mark의 score를 4.42로 설정
pDer->showStudent(); // 4.42 : 20 출력
pBase->showStudent(); // 컴파일 오류. Person에서 Student의 멤버 접근 불가
}
출력 :
20
4.42 : 20
int main() {
Student mark;
Student *pDer;
Person *pBase = &mark; // 업 캐스팅
pBase->setAge(20); // mark의 age를 20으로 설정
pBase->show(); // 20 출력
pDer = (Student *)pBase; // 다운 캐스팅
pDer->setScore(4.42); // mark의 score를 4.42로 설정
pDer->showStudent(); // 4.42 : 20 출력
}
class Person { // 기본 클래스 Person 선언
protected:
int age; // protected 변수이므로 파생 클래스 멤버함수까지만 접근 가능
public:
void setAge(int age) { this->age = age; }
void show() { cout << age; }
};
class Student : public Person { // Person을 상속받는 Student 선언
double score;
public:
void setScore(double score) { this->score = score; }
void showStudent() {
cout << score << ' : ';
cout << age; // protected 변수를 파생 클래스에서 접근
}
};
class Derived : public Base { ... };
class Derived : protected Base { ... };
class Derived : private Base { ... };
class Person {
public:
int age;
void eat() { ... }
void sleep() { ... }
};
class Student : public Person {
protected:
string studentID;
public:
void study() { ... }
};
class Employee : public Person {
protected:
string employeeID;
public:
void work() { ... }
};
// Intern은 Student와 Employee를 모두 상속
class Intern : public Student, public Employee { // 다중 상속 선언
public:
Intern(int age, string& sID, string& eID) {
this->age = age; // Person으로부터 상속, 모호성 발생
this->studentID = sID; // Student로부터 상속
this->employeeID = eID; // Employee로부터 상속
}
};
int main() {
Intern Bob(24, "2024E7403", "20253047"); // 모호성으로 24 전달 불가
while(true) {
Bob.eat(); // Person으로부터 상속, 모호성 발생
Bob.study(); // Student로부터 상속
Bob.work(); // Employee로부터 상속
Bob.sleep(); // Person으로부터 상속, 모호성 발생
}
}
class Person { ... };
// 가상 상속
class Student : virtual public Person { ... };
// 가상 상속
class Employee : virtual public Person { ... };
// 가상 상속을 통해 공통의 Person 기본 클래스를 한 번만 포함
class Intern : public Student, public Employee { ... };