• 코드:
​x
 
1
#include <iostream>
2
using namespace std;
3
​
4
class Person
5
{
6
private:
7
    string name_;
8
    int age_;
9
public:
10
    Person(const string& name, int age);    // 기초 클래스 생성자의 선언 
11
    void ShowPersonInfo();
12
};
13
​
14
class Student : public Person
15
{
16
private:
17
    int student_id_;
18
public:
19
    Student(int sid, const string& name, int age);  // 파생 클래스 생성자의 선언 
20
    void ShowPersonInfo();  // 파생 클래스에서 상속받은 멤버 함수의 재정의 
21
};
22
​
23
int main(void)
24
{
25
    Person* ptr_person;
26
    Person lee("순신", 35);
27
    Student hong(123456789, "길동", 29);
28
    
29
    ptr_person = &lee;
30
    ptr_person->ShowPersonInfo();
31
    ptr_person = &hong;
32
    ptr_person->ShowPersonInfo();
33
    
34
    return 0;
35
}
36
​
37
Person::Person(const string& name, int age) // 기초 클래스 생성자의 정의 
38
{
39
    name_ = name;
40
    age_ = age;
41
}
42
​
43
void Person::ShowPersonInfo()
44
{
45
    cout << name_ << "의 나이는 " << age_ << "살입니다." << endl;
46
}
47
​
48
Student::Student(int sid, const string& name, int age) : Person(name, age)  // 파생 클래스 생성자의 정의 
49
{
50
    student_id_ = sid;
51
}
52
​
53
void Student::ShowPersonInfo()
54
{
55
    cout << "이 학생의 학번은 " << student_id_ << "입니다." << endl;
56
}
표준입력 & 실행옵션