p.339의 상속관련 예제입니다.
● human.h
#include <iostream> #include <string> using namespace std; #ifndef HUMAN_H #define HUMAN_H class Human { protected: string name; int age; public: Human(); Human(string name, int age); ~Human(); void setName(string v_name); string getName(void); void setAge(int v_age); int getAge(void); void print(void); }; #endif
● human.cpp
#include "human.h" Human::Human() { /* Default constructor */ cout << "Human default constructor" << "\n"; } Human::Human(string name, int age) { setName(name); setAge(age); cout << "Human second constructor" << "\n"; } Human::~Human() { /* Do nothing */ cout << "Human default destructor" << "\n"; } void Human::setName(string v_name) { name = v_name; return; } string Human::getName() { return name; } void Human::setAge(int v_age) { age = v_age; return; } int Human::getAge() { return age; } void Human::print(void) { cout << "Name : " << name << "\tAge : " << age << "\n"; return; }
● student.h
#ifndef HUMAN_H #include "human.h" #endif #ifndef STUDENT_H #define STUDENT_H class Student : public Human { protected: string major; public: Student(); Student(string name, int age, string major); ~Student(); void setMajor(string v_major); string getMajor(void); void print(void); }; #endif
● student.cpp
#include "student.h" Student::Student() { /* default constructor */ cout << "Student default constructor" << "\n"; } Student::Student(string name, int age, string major) { setName(name); setAge(age); setMajor(major); cout << "Student second constructor" << "\n"; } Student::~Student() { /* Do nothing */ cout << "Student default destructor" << "\n"; } void Student::setMajor(string v_major) { major = v_major; } string Student::getMajor(void) { return major; } void Student::print(void) { cout << "Name : " << name << "\tAge : " << age << "\tMajor : " << major << "\n"; return; }
● main.cpp
#include <iostream> #include <string> using namespace std; #include "human.h" #include "student.h" int main() { Human a("춘향", 18); Human b("몽룡", 21); Human c("사또", 50); a.print(); b.print(); c.print(); Student d("명진", 21, "컴퓨터"); Student e("미현", 22, "경영"); Student f("용준", 24, "전자"); d.print(); e.print(); f.print(); return 0; }※ 뭐 질문이 없어서, 그냥 손에 잡히는데로 하렵니다. 그나저나 구글의 소스 플러그인은 정말 보기가 좋네요.
'Studies > C++ Espresso' 카테고리의 다른 글
9장 Programming 1. 은행계좌 (0) | 2011.12.13 |
---|---|
Programming 08-07 (p.338) 클래스 설계 (0) | 2011.12.06 |
[Review] Chapter 01. p.14 ~ 15 Name Space 와 변수 (0) | 2011.09.06 |
[Review] Chapter 01. p.06 - 객체지향방법 (Object-oriented approach)의 목적 (0) | 2011.09.06 |
뭐부터 할까? (4) | 2011.09.06 |