Starting Out with C++: Early Objects 5th Edition

Slides:



Advertisements
Similar presentations
3. C++와 객체지향 C++ 코딩 방법 객체 단위로 2 개의 파일 인터페이스 파일 구현파일
Advertisements

Vision System Lab, Sang-Hun Han
C++ Tutorial 1 서강대학교 데이터베이스 연구실.
Chapter 7 ARP and RARP.
명품 C++ 프로그래밍 3장. 클래스와 객체.
명품 C++ 8장 상속.
명품 C++ 4장. 객체 포인터와 객체 배열, 객체의 동적 생성.
Power C++ 제6장 포인터와 문자열.
C++ Espresso 제3장 배열과 포인터.
C++ Espresso 제3장 배열과 포인터.
C++ Espresso 제1장 기초 사항.
C++ Espresso 제2장 제어문과 함수.
Internet Computing KUT Youn-Hee Han
Java Presentation 중간 시험2 풀이
강좌명 : C++프로그래밍 (C++ Programming)
C++ 프로그래밍 년 2학기 전자정보공학대학 컴퓨터공학부.
제6장 객체배열과 벡터 객체 배열을 이해한다. 벡터(vector) 클래스를 사용할 수 있다.
10장 예외 처리 프로그래밍 언어론 10.6 Pascal과 C의 에러 처리 10.1 설계 주제 10.2 PL/I의 예외 처리
명품 C++ 13장 예외 처리와 C 언어와의 링크 지정.
제 6 장 데이터 타입 6.1 데이터 타입 및 타입 정보 6.2 타입의 용도 6.3 타입 구성자 6.4 사례 연구
C++ Exspresso 제5장 클래스의 기초.
Internet Computing KUT Youn-Hee Han
2주 실습강의 Java의 기본문법(1) 인공지능연구실.
8. 객체와 클래스 (기본).
명품 JAVA Programming.
C++ Espresso 제9장 다형성.
10장 객체-지향 프로그래밍 II ©창병모.
Starting Out with C++: Early Objects 5th Edition
10장 템플릿과 표준 템플릿 라이브러리(STL)
배열, 포인터, 참조 배열은 같은 형을 가지는 변수들의 묶음이다..
명품 C++ 8장 상속.
자바 5.0 프로그래밍.
C++ Espresso 제6장 생성자와 소멸자.
7장 클래스.
명품 C++ 7장 프렌드와 연산자 중복.
18장. 헤더 파일과 구현 파일 01_ 헤더 파일과 구현 파일의 사용.
14장. 함수 1 01_ 함수의 기본 02_ 인자의 전달.
Chapter 05. 클래스 완성. chapter 05. 클래스 완성 01. 복사 생성자 복사 생성(Copy Construction) 생성될 때 자신과 같은 타입의 객체를 변수로 받아, 이 객체와 같은 값을 갖는 새로운 객체를 생성하는 것 명시적인 생성 과정뿐만.
C ++ 프로그래밍 시작.
정적 멤버 변수/정적 멤버 함수 - friend 함수/클래스 template
Chapter 1 C++ 기초 Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
C++ Programming: chapter 7 – inheritence
C++ 개요 객체지향 윈도우즈 프로그래밍 한국성서대학교 유일선
스택(Stack) 김진수
C++ 프로그래밍 년 2학기 전자정보공학대학 컴퓨터공학부.
adopted from KNK C Programming : A Modern Approach
Chapter 2 Lexical Elements, Operators, and the C System
제2장 데이터 및 수식.
추상 데이터 타입 정의하기 Defining abstract data types
타입, 연산자 Chapter 5, 6 Kum Deuk Kyu , Ph. D. Spring 2015
가상함수와 추상 클래스.
메소드와 클래스 정의 및 문제 풀이 Method and Class Define and Problem Solve
제2장 제어구조와 배열 if-else 문에 대하여 학습한다. 중첩 if-else 문에 대하여 학습한다.
Introduction to Programming Language
4. 고급변수 사용 : 포인터와 관련하여 메모리 바라보기
루프와 카운트 Looping and counting
문자열 처리하기 working with Strings
멤버 함수인 operator+()가 실행, 또는 전역 함수인 operator+()가 실행 Point p3 = p1+p2; 에서
C-언어와 기반구조 정보보호학과 이정수 교수.
Signature, Strong Typing
제 11장. 템플릿과 STL 학기 프로그래밍언어및실습 (C++).
3장,4장 발표 서정우.
03. 메모리 관리 C++ 프로그램에서 다룰 수 있는 메모리의 종류
Signature, Strong Typing
포인터와 배열 조 병 규 한 국 교 통 대 학 교 SQ Lab..
제 8장. 클래스의 활용 학기 프로그래밍언어및실습 (C++).
새로운 타입 정의하기 Defining new types
캡슐화 (Encapsulation) 두원공과대학 소프트웨어개발과 이 원 주.
C++ 언어의 특징
윤성우의 열혈 C++ 프로그래밍 윤성우 저 열혈강의 C++ 프로그래밍 개정판 Chapter 02. C언어 기반의 C++ 2.
Presentation transcript:

Starting Out with C++: Early Objects 5th Edition Chapter 11 클래스와 객체 지향 프로그래밍 Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved

목 차 11.1 this 포인터와 const 멤버함수 11.2 정적 멤버 11.3 클래스의 프렌드 11.4 멤버별 배정 목 차 11.1 this 포인터와 const 멤버함수 11.2 정적 멤버 11.3 클래스의 프렌드 11.4 멤버별 배정 11.5 복사 생성자 11.6 연산자 과적 11.7 자료형 변환 연산자 © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 2

목 차(계속) 11.8 변환 생성자 11.9 객체 결합 11.10 상속 11.11 보호 멤버와 클래스 접근 목 차(계속) 11.8 변환 생성자 11.9 객체 결합 11.10 상속 11.11 보호 멤버와 클래스 접근 11.12 생성자, 소멸자 그리고 상속 11.13 기본 클래스 함수의 오버라이드 © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 3

11.1 this 포인터와 const 멤버함수 this 포인터: - 맴버 함수에게 전달된 묵시적인 매개변수 - 호출 함수의 객체를 가리킨다. const 멤버 함수: - 멤버 함수의 호출 객체를 수정하지 않는다. See pr11-01.cpp © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 4

this 포인터의 사용 같은 이름을 가진 매개변수에 의해 숨겨질 수 있는 멤버에 접근하기 위해 사용될 수 있다. : class SomeClass { private: int num; public: void setNum(int num) { this->num = num; } }; 같은 이름일 때 num © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 5

this 포인터의 사용 // Used by ThisExample.cpp class Example { int x; public: Example(int a){ x = a;} void setValue(int); void printAddressAndValue(); }; © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 6

this 포인터의 사용 #include "ThisExample.h" #include <iostream> using namespace std; //***************************************** //set value of object * void Example::setValue(int a) { x = a; } // print address and value * void Example::printAddressAndValue() cout << "The object at address " << this << " has “ // 0x241ff5c 0x241ff58 << "value " << (*this).x << endl; // 10 20 } // this->x © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 7

this 포인터의 사용 //This program illustrates the this pointer #include <iostream> #include "ThisExample.h" using namespace std; int main() { Example ob1(10), ob2(20); // print addresses of the two objects cout << "Addresses of objects are " << &ob1 << " and " << &ob2 << endl; // print addresses and values from within the // member function ob1.printAddressAndValue(); ob2.printAddressAndValue(); return 0; } © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 8

const 멤버함수 키워드 const로 선언 const가 매개변수 목록 뒤에 올 때, int getX()const 이 함수는 객체의 수정을 방지한다. const가 매개변수 목록에서 나타날 때, int setNum (const int num) 이 함수는 매개변수의 수정을 방지한다. 매개변수는 read-only. © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 9

11.2 정적 멤버 정적 변수: - 클래스의 모든 객체에 의해 공유 정적 멤버 함수: - 정적 멤버 변수에 접근하기 위해 사용 - 객체가 생성되기 전에 호출될 수 있다. See pr11-02.cpp, budget.h © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 10

정적 멤버 변수 키워드 static 과 함께 클래스 내에서 선언되어야 한다: { public: class IntVal { public: intVal(int val = 0) { value = val; valCount++ } int getVal(); void setVal(int); private: int value; static int valCount; }; © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 11

정적 멤버 변수 2) 클래스 외부에서 반드시 정의되어야 한다: class IntVal { //In-class declaration static int valCount; //Other members not shown }; //Definition outside of class int IntVal::valCount = 0; © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 12

정적 멤버 변수 3) 클래스의 어떤 객체에 의해서도 접근되거나 수정될 수 있다: 한 객체에 대한 수정이 클래스의 다른 객체에 대해서도 가시적이다: IntVal val1, val2; valCount 2 val1 val2 © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 13

정적 멤버 변수 사용 #ifndef BUDGET_H #define BUDGET_H // Budget class declaration class Budget { private: static double corpBudget; double divBudget; public: Budget() { divBudget = 0; } void addBudget(double b) { divBudget += b; corpBudget += divBudget; } double getDivBudget() { return divBudget; } double getCorpBudget() { return corpBudget; } }; #endif © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 14

정적 멤버 변수 사용 © 2006 Pearson Education. // This program demonstrates a static class member variable. #include <iostream> #include <iomanip> #include "budget.h" // For Budget class declaration using namespace std; double Budget::corpBudget = 0; // Definition of static member of // Budget class const int N_DIVISIONS = 4; int main() { Budget divisions[N_DIVISIONS]; int count; for (count = 0; count < N_DIVISIONS; count++) double bud; cout << "Enter the budget request for division "; cout << (count + 1) << ": "; cin >> bud; divisions[count].addBudget(bud); } cout << setprecision(2); cout << showpoint << fixed; cout << "\nHere are the division budget requests:\n"; cout << "\tDivision " << (count + 1) << "\t$ "; cout << divisions[count].getDivBudget() << endl; cout << "\tTotal Budget Requests:\t$ "; cout << divisions[0].getCorpBudget() << endl; return 0; © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 15

정적 멤버 함수 1) 함수 반환형 앞에 static을 사용하여 선언: { public: class IntVal { public: static int getValCount() { return valCount; } private: int value; static int valCount; }; See pr11-03.cpp © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 16

정적 멤버 함수 2) 클래스 이름을 사용하여 클래스 객체와 독립적으로 호출할 수 있다: cout << IntVal::getValCount(); 3) 클래스의 객체가 생성되기 전에도 호출될 수 있다. 4) 주로 클래스의 static 멤버 변수를 다루기 위해 사용된다. 5) 정적 멤버 함수에서 this 포인터를 사용할 수 없다.(객체 인스턴스와 무관하게 호출될 수 있기 때문) 정적 멤버 함수에서 멤버 변수를 사용할 수 없다. See pr11-03.cpp, budget2.cpp, and budget2.h © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 17

정적 멤버 함수 사용 // Budget class declaration budget2.h class Budget // 부서 예산 요청 전에 본부 예산 요청 { private: static double corpBudget; double divBudget; public: Budget() { divBudget = 0; } void addBudget(double b) { divBudget += b; corpBudget += divBudget; } double getDivBudget() { return divBudget; } static double getCorpBudget() { return corpBudget; } static void mainOffice(double); }; © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 18

정적 멤버 함수 사용 double Budget::corpBudget = 0; // Definition of static member of // Budget class //********************************************************** // Definition of static member function mainOffice * // This function adds the main office's budget request to * // the corpBudget variable. * void Budget::mainOffice(double moffice) { corpBudget += moffice; } © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 19

정적 멤버 함수 사용 © 2006 Pearson Education. int main() { const int N_DIVISIONS = 4; double amount; int count; cout << "Enter the main office's budget request: "; cin >> amount; Budget::mainOffice(amount); // 부서 예산 요청 전에 본부 예산 요청(정적 멤버 함수) Budget divisions[N_DIVISIONS]; for (count = 0; count < N_DIVISIONS; count++) double bud; cout << "Enter the budget request for division "; cout << (count + 1) << ": "; cin >> bud; divisions[count].addBudget(bud); } cout << setprecision(2); cout<< showpoint << fixed; cout << "\nHere are the division budget requests:\n"; cout << "\tDivision " << (count + 1) << "\t$ "; cout << divisions[count].getDivBudget() << endl; cout << "\tTotal Requests (including main office): $ "; cout << Budget::getCorpBudget() << endl; // 정적 멤버 함수 호출 return 0; // cout << divisions[0].getCorpBudget() 대치 가능 © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 20

11.3 클래스의 프렌드 friend 함수: 클래스의 멤버는 아니지만 클래스의 비공개 멤버에 접근할 수 있는 함수. 프렌드 함수는 외부 함수이거나 다른 클래스의 멤버 함수이다. 함수 원형 내에서 키워드 friend 를 사용하여 클래스의 프렌드로 선언된다. © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 21

프렌드 함수 선언 외부 함수: class aClass { private: int x; friend void fSet(aClass &c, int a); }; void fSet(aClass &c, int a) c.x = a; } See pr11-04.cpp, auxil.h, budget3.h, auxil.cpp, and budget3.cpp © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 22

프렌드 함수 선언 2) 다른 클래스의 멤버 함수: class aClass { private: int x; friend void OtherClass::fSet (aClass &c, int a); }; class OtherClass { public: void fSet(aClass &c, int a) { c.x = a; } © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 23

프렌드 클래스 선언 전체 클래스가 클래스의 friend 로 선언될 수 있다: {private: int x; class aClass {private: int x; friend class frClass; }; class frClass {public: void fSet(aClass &c,int a){c.x = a;} int fGet(aClass c){return c.x;} © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 24

프렌드 클래스 선언 frClass가 aClass의 프렌드이면, frClass의 모든 멤버 함수는 aClass의 모든 멤버(비보호 멤버 포함)에 대해 접근권한을 가진다. 일반적으로는 클래스의 비보호 멤버에 접근할 필요가 있는 함수 만에 대해 프렌드로 선언하는 것이 바람직하다. © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 25

11.4 멤버별 배정 한 객체에 다른 객체를 배정하거나 다른 객체로 초기화할 때 배정 연산자 “=” 을 사용할 수 있다. (멤버 별로 복사) 예 (class V): V v1, v2; .// statements that assign .// values to members of v1 v2 = v1; // 배정 V v3 = v2; // 초기화 See pr11-05.cpp © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 26

11.5 복사 생성자 복사 생성자(copy constructor) :새로이 생성된 객체가 같은 클래스의 다른 객체에 의해 초기화될 때 사용되는 특별한 생성자 디폴트(default) 복사 생성자는 멤버 별로 복사한다. 디폴트 복사 생성자는 대부분의 경우 잘 동작한다. See pr11-06.cpp © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 27

복사 생성자 객체가 동적 기억장소에 대한 포인터를 가질 때 문제가 발생한다: class CpClass {private: int *p; public: CpClass(int v=0) { p = new int; *p = v;} ~CpClass(){delete p;} }; 주의 © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 28

디폴터 복사 생성자는 기억장소 공유 문제를 야기 CpClass c1(5); if (true) { CpClass c2; c2 = c1; } // c1 is corrupted // when c2 goes // out of scope 해지 c1.p c2.p 5 주의 © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 29

동적 기억장소 공유에 따른 문제점(디폴터 복사 생성자) 다른 객체에 의해 아직 사용 중인 기억장소를 한 객체의 소멸자에 의해 삭제한다. 한 객체에 대한 기억장소의 수정이 기억장소를 공유하고 있는 다른 객체에 영향을 미친다. 주의 See pr11-07.cpp, NumberArray.h, and NumberArray.cpp 프로그램 11-7:p.651 © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 30

동적 기억장소 공유에 따른 문제점 class NumberArray // NumberArray.h { private: double *aPtr; int arraySize; public: NumberArray(int size, double value); //~NumberArray(){ if (arraySize > 0) delete [ ] aPtr;} //commented out to avoid problems with default copy constructor void print(); void setValue(double value); }; © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 31

동적 기억장소 공유에 따른 문제점 NumberArray::NumberArray(int size, double value) { arraySize = size; aPtr = new double[arraySize]; setValue(value); } void NumberArray::setValue(double value) for(int index = 0; index < arraySize; index++) aPtr[index] = value; void NumberArray::print() cout << aPtr[index] << " "; © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 32

동적 기억장소 공유에 따른 문제점 int main() { NumberArray first(3, 10.5); //Make second a copy of first object NumberArray second = first; cout << setprecision(2) << fixed << showpoint; cout << "Value stored in first object is "; first.print(); cout << endl << "Value stored in second object is "; second.print(); cout << endl << "Only the value in second object will be changed." << endl; //Now change value stored in second object second.setValue(20.5); return 0; } © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 33

프로그래머 정의 복사 생성자 복사 생성자는 자신의 클래스에 대한 참조를 매개변수로 가진다. NumberArray::NumberArray(NumberArray &obj) 복사 생성자는 생성될 객체를 초기화하기 위해 매개변수로 전달된 객체의 자료를 사용한다. 참조 매개변수의 문제점을 방지하기 위해 const로 선언한다. (단지 복사본을 만든다) © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 34

프로그래머 정의 복사 생성자 복사 생성자는 기억장소 공유에 의해 야기되는 문제를 해결할 수 있다. 새로운 객체의 동적 멤버 자료를 위해 독립적인 기억장소를 할당한다. 새로운 객체의 포인터가 독립된 동적 기억장소를 가리키게 한다. 원 객체에서 새 객체로 포인터가 아니라 자료를 복사하게 한다. See pr11-08.cpp, NumberArray2.h, and NumberArray2.cpp © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 35

복사 생성자 예 class CpClass { int *p; public: CpClass(const CpClass &obj) { p = new int; *p = *obj.p; } CpClass(int v=0) { p = new int; *p = v; } ~CpClass(){delete p;} }; © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 36

복사 생성자 자동 호출 객체 생성시 초기화 구문(배정 연산자는 연산자 과적을 사용하여야 한다) 함수의 매개변수로 객체 값이 전달될 때 객체를 반환하는 함수 © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 37

11.6 연산자 과적 연산자( =, +, 기타)는 클래스 객체의 사용을 위하여 재정의 될 수 있다. 과적 연산자의 함수 이름은 operator 다음에 연산자 기호가 온다. 예, operator+ 는 + 연산자의 과적 함수, operator= 는 = 연산자의 과적 함수 © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 38

연산자 과적 연산자는 과적될 수 있다. - 인스턴스 멤버 함수 - 프렌드 함수 과적된 연산자는 같은 수의 매개변수를 가져야 한다. 예로서, operator= 는 두 개의 매개변수를 가져야 한다.(= 배정 연산자는 두 개의 매개변수를 취한다) © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 39

연산자 과적 :인스턴스 멤버 인스턴스 멤버로 과적된 이진 연산자는 오른쪽의 피연산자를 나타내는 하나의 매개변수 만을 요구한다: class OpClass { int x; public: OpClass operator+(OpClass right); }; See pr11-09.cpp, Overload.h, and Overload.cpp © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 40

연산자 과적 :인스턴스 멤버 과적된 이진 연산자의 왼쪽 피연산자는 호출한 객체이다. 묵시적인 왼쪽 매개변수는 this 포인터에 의해 접근된다. OpClass OpClass::operator+(OpClass r) { OpClass sum; sum.x = this->x + r.x; return sum; } © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 41

과적된 연산자의 호출하기 연산자는 멤버 함수 형태로 호출될 수 있다: OpClass a, b, s; s = a.operator+(b); 다음과 같은 방법으로 호출될 수 있다: s = a + b; See feetinch2.h, feetinch2.cpp, pr11-10.cpp © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 42

배정연산자 과적 배정연산자 과적을 사용하면 객체가 동적 기억장소에 대한 포인터를 포함할 때 객체 배정에서 발생하는 문제점을 해결할 수 있다. 배정연산자는 인스턴스 멤버 함수로서 자연스럽게 과적된다. 다음과 같은 cascaded 배정을 허용하기 위해 배정된 객체의 값을 반환할 필요가 있다. a = b = c; © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 43

배정연산자 과적 배정연산자 과적(멤버 함수): { int *p; public: CpClass(int v=0) class CpClass { int *p; public: CpClass(int v=0) { p = new int; *p = v; ~CpClass(){delete p;} CpClass operator=(CpClass); }; © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 44

배정연산자 과적 클래스의 객체를 반환: 배정 연산자 호출: { *p = *r.p; return *this; }; CpClass CpClass::operator=(CpClass r) { *p = *r.p; return *this; }; 배정 연산자 호출: CpClass a, x(45); a.operator=(x); a = x; © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 45

연산자 과적의 유의사항 연산자의 의미를 변경할 수 없다. 대부분의 연산자는 과적할 수 있다. 연산자의 피연산자 수를 변경할 수 없다. 과적 불가 연산자: ?: . .* sizeof © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 46

연산자 과적 유형 ++, -- 연산자는 전위/후위 표기에 따라 서로 다른 방법으로 과적된다. 과적된 관계 연산자는 bool 값을 반환하여야 한다. 과적된 스트림 연산자 >>, << 는 istream, ostream 객체를 반환하여야 하고, 매개 변수로 istream, ostream 객체를 취한다. See feetinch3.h feetinch3.cpp, pr11-11.cpp for first bullet; See feetinch4.h, feetinch4.cpp, and pr11-12.cpp for second bullet; See feetinch5.h, feetinch5.cpp, and pr11-13.cpp for the last bullet. © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 47

연산자 과적 예 © 2006 Pearson Education. class FeetInches; // Forward Declaration // Function Prototypes for Overloaded Stream Operators ostream &operator<<(ostream &, FeetInches &); istream &operator>>(istream &, FeetInches &); // A class to hold distances or measurements expressed // in feet and inches. class FeetInches { private: int feet; int inches; void simplify(); // Defined in feetinch5.cpp public: FeetInches(int f = 0, int i = 0) { feet = f; inches = i; simplify(); } void setData(int f, int i) int getFeet() { return feet; } int getInches() { return inches; } FeetInches operator + (const FeetInches &)const; // Overloaded + FeetInches operator - (const FeetInches &)const; // Overloaded - FeetInches operator++(); // Prefix ++ FeetInches operator++(int); // Postfix ++ bool operator>(const FeetInches &)const; bool operator<(const FeetInches &)const; bool operator==(const FeetInches &)const; friend ostream &operator<<(ostream &, FeetInches &); friend istream &operator>>(istream &, FeetInches &); }; © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 48

void FeetInches::simplify() { inches = 12*feet + inches; feet = inches / 12; inches = inches % 12; } //*********************************************************** // Overloaded binary + operator. * FeetInches FeetInches::operator+(const FeetInches &right)const FeetInches temp; temp.inches = inches + right.inches; temp.feet = feet + right.feet; temp.simplify(); return temp; //********************************************************** // Overloaded binary - operator. * FeetInches FeetInches::operator-(const FeetInches &right)const temp.inches = inches - right.inches; temp.feet = feet - right.feet; © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 49

Chapter 11 Starting Out with C++: Early Objects 5/e slide 50 //************************************************************* // Overloaded prefix ++ operator. Causes the inches member to * // be incremented. Returns the incremented object. * FeetInches FeetInches::operator++() { ++inches; simplify(); return *this; } //*************************************************************** // Overloaded postfix ++ operator. Causes the inches member to * // be incremented. Returns the value of the object before the * // increment. * FeetInches FeetInches::operator++(int) FeetInches temp(feet, inches); inches++; return temp; // Overloaded > operator. Returns true if the current object is * // set to a value greater than that of right. * bool FeetInches::operator>(const FeetInches &right)const if (feet > right.feet) return true; else if (feet == right.feet && inches > right.inches) else return false; © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 50

Chapter 11 Starting Out with C++: Early Objects 5/e slide 51 //*************************************************************** // Overloaded < operator. Returns true if the current object is * // set to a value less than that of right. * bool FeetInches::operator<(const FeetInches &right) const { return right > *this; } //**************************************************************** // Overloaded == operator. Returns true if the current object is * // set to a value equal to that of right. * bool FeetInches::operator==(const FeetInches &right)const if (feet == right.feet && inches == right.inches) return true; else return false; //******************************************************** // Overloaded << operator. Gives cout the ability to * // directly display FeetInches objects. * ostream &operator<<(ostream &strm, FeetInches &obj) strm << obj.feet << " feet, " << obj.inches << " inches"; return strm; // Overloaded >> operator. Gives cin the ability to * // store user input directly into FeetInches objects. * istream &operator>>(istream &strm, FeetInches &obj) strm >> obj.feet >> obj.inches; © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 51

FeetInches first, second, third; int main() // 프로그램 11-13 { FeetInches first, second, third; cout << "Enter a distance in feet and inches:\n"; cin >> first; cout << "Enter another distance in feet and inches:\n"; cin >> second; cout << "The values you entered are:\n"; cout << first << " and " << second; return 0; } © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 52

FeetInches first, second, third; int f, i; int main() // 프로그램 11-12 { FeetInches first, second, third; int f, i; cout << "Enter a distance in feet and inches: "; cin >> f >> i; first.setData(f, i); cout << "Enter another distance in feet and inches: "; second.setData(f, i); if (first == second) cout << "First is equal to second.\n"; if (first > second) cout << "First is greater than second.\n"; if (first < second) cout << "First is less than second.\n"; return 0; } © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 53

int main() // 프로그램 11-11 { FeetInches first, second(1, 5); int count; cout << "Demonstrating prefix ++ operator.\n"; for (count = 0; count < 12; count++) first = ++second; cout << "first: " << first.getFeet() << " feet, "; cout << first.getInches() << " inches. "; cout << "second: " << second.getFeet() << " feet, "; cout << second.getInches() << " inches.\n"; } cout << "\nDemonstrating postfix ++ operator.\n"; first = second++; return 0; © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 54

FeetInches first, second, third; int f, i; int main() // 프로그램 11-10 { FeetInches first, second, third; int f, i; cout << "Enter a distance in feet and inches: "; cin >> f >> i; first.setData(f, i); cout << "Enter another distance in feet and inches: "; second.setData(f, i); third = first + second; cout << "first + second = "; cout << third.getFeet() << " feet, "; cout << third.getInches() << " inches.\n"; third = first - second; cout << "first - second = "; return 0; } © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 55

[] 연산자 과적 첨자 검사를 수행할 수 있는 배열과 같은 클래스를 생성 과적된 []는 객체의 참조를 반환한다.(객체 자신이 아니라) See Intarray.h, Intarray.cpp, pr11-15.cpp © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 56

[] 연산자 과적 예 class IntArray { private: int *aptr; int arraySize; void subError(); // Handles subscripts out of range public: IntArray(int); // Constructor IntArray(const IntArray &); // Copy constructor ~IntArray(); // Destructor int size() { return arraySize; } int &operator[](int); // Overloaded [] operator }; © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 57

Chapter 11 Starting Out with C++: Early Objects 5/e slide 58 //******************************************************* // Constructor for IntArray class. Sets the size of the * // array and allocates memory for it. * IntArray::IntArray(int s) { arraySize = s; aptr = new int [s]; for (int count = 0; count < arraySize; count++) *(aptr + count) = 0; } //****************************************************** // Copy constructor for IntArray class. * IntArray::IntArray(const IntArray &obj) arraySize = obj.arraySize; aptr = new int [arraySize]; for(int count = 0; count < arraySize; count++) *(aptr + count) = *(obj.aptr + count); // Destructor for IntArray class. * IntArray::~IntArray() if (arraySize > 0) delete [] aptr; © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 58

//*********************************************************** // subError function. Displays an error message and * // terminates the program when a subscript is out of range. * void IntArray::subError() { cout << "ERROR: Subscript out of range.\n"; exit(0); } //******************************************************* // Overloaded [] operator. The argument is a subscript. * // This function returns a reference to the element * // in the array indexed by the subscript. * int &IntArray::operator[](int sub) if (sub < 0 || sub >= arraySize) subError(); return aptr[sub]; © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 59

int main() // 프로그램 11-15 { IntArray table(10); int x; //Loop index // Store values in the array for (x = 0; x < table.size(); x++) table[x] = (x * 2); // Display the values in the array cout << table[x] << " "; cout << endl; // Use the built-in + operator on array elements table[x] = table[x] + 5; // Use the built-in ++ operator on array elements table[x]++; return 0; } © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 60

//of the IntArray class. #include <iostream> //This program demonstrates the bounds-checking capabilities // 프로그램 11-16 //of the IntArray class. #include <iostream> #include "intarray.h" using namespace std; int main() { IntArray table(10); int x; // Loop index // Store values in the array for (x = 0; x < table.size(); x++) table[x] = x; // Display the values in the array cout << table[x] << " "; cout << endl; cout << "Attempting to store outside the array bounds:\n"; table[table.size()] = 0; return 0; } © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 61

11.7 형 변환 연산자 변환 연산자(Conversion Operators)는 컴파일러에게 클래스의 객체를 다른 형의 값으로 변환하는 방법을 알려주는 멤버 함수이다. 변환 연산자에 의해 제공되는 변환 정보는 컴파일러에 의해 배정, 초기화, 매개변수 전달 시에 자동적으로 사용된다. See feetinch6.h, feetinch6.cpp, pr11-17.cpp © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 62

변환 연산자의 문법 변환 연산자는 변환되어지는 클래스의 멤버 함수이어야 한다. 연산자 이름은 변환하려는 자료의 이름이다. 변환 연산자는 반환형을 기술하지 않는다. © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 63

변환 연산자의 예 클래스 IntVal에서 정수로 변환: class IntVal { int x; public: IntVal(int a = 0){x = a;} operator int(){return x;} }; 배정 연산 시 자동 변환: IntVal obj(15); int i; i = obj; cout << i; // prints 15 See feetinch6.h, feetinch6.cpp, and pr11-17.cpp © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 64

11.8 변환 생성자 변환 생성자는 그 클래스 외의 형을 가지는 단일 매개변수를 가지는 생성자이다. public: class CCClass { int x; public: CCClass() //default CCClass(int a, int b); CCClass(int a); //convert CCClass(string s); //convert }; See Convert.h, Convert.cpp, and pr11-18.cpp © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 65

변환 생성자 예 C++ string 클래스는 C-strings 으로부터 변환하는변환 생성자를 가진다: { public: class string { public: string(char *); //convert … }; © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 66

변환 생성자 사용 변환 생성자는 매개변수로 전달된 값으로부터 객체를 생성하기 위해 컴파일러에 의해 자동으로 호출된다: string s("hello"); //convert C-string CCClass obj(24); //convert int 컴파일러는 다음과 같은 배정문에 의해 변환 생성자가 호출되게 한다: string s = "hello"; //convert C-string CCClass obj = 24; //convert int © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 67

변환 생성자 사용 변환 생성자는 매개변수로 그 클래스 형을 취하는 함수에게 다른 자료형의 매개변수를 취할 수 있게한다: void myFun(string s); // needs string // object myFun("hello"); // accepts C-string void myFun(CCClass c); myFun(34); // accepts int © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 68

변환 생성자 사용 예 class IntClass { private: int value; public: //convert constructor from int IntClass(int intValue) value = intValue; } int getValue(){ return value; } }; © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 69

//******************************************* // This function returns an int even though * // an IntClass object is declared as the * // return type * IntClass f(int intValue) { return intValue; } // Prints the int value inside an IntClas * // object * void printValue(IntClass x) cout << x.getValue(); © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 70

//Function prototypes void printValue(IntClass); IntClass f(int); int main() { //initialize with an int IntClass intObject = 23; cout << "The value is " << intObject.getValue() << endl; //assign an int intObject = 24; cout << "The value is " << intObject.getValue() << endl; //pass an int to a function expecting IntClass cout << "The value is "; printValue(25); cout << endl; //demonstrate conversion on a return intObject = f(26); printValue(intObject); return 0; } © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 71

11.9 객체 결합 객체 결합(Object composition): 클래스의 데이터 멤버가 다른 클래스의 객체일 수 있다. 클래스 간의 ‘has a’ 관계를 모델링 – 포함 클래스는 포함된 클래스의 인스턴스를 가진다. 구조체 내의 구조체에 대한 표기와 같다. See pr11-19.cpp © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 72

객체 결합 예 class StudentInfo { private: string firstName, LastName; string address, city, state, zip; ... }; class Student StudentInfo personalData; © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 73

객체 결합 예 © 2006 Pearson Education. class Date { private: string month; int day; int year; public: void setDate(string month, int day, int year) this->month = month; this->day = day; this->year = year; } Date(string month, int day, int year) setDate(month, day, year); Date() setDate("January", 1, 1900); string getMonth() { return month; } int getDay() { return day; } int getYear() { return year; } }; © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 74

class Acquaintance { private: string name; Date dob; // Date of birth public: Acquintance(string name, string month, int day, int year) this->name = name; dob.setDate(month, day, year); } void print() cout << name << "\'s birthday is on " << dob.getMonth() << " " << dob.getDay() << ", " << dob.getYear(); }; int main() Acquaintance buddy("Bill Stump", "February", 5, 1975); buddy.print(); return 0; © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 75

11.10 상속 상속(Inheritance) : 이전 클래스에 새로운 멤버를 추가함으로써 새로운 클래스를 생성하는 방법 새로운 클래스는 이전 클래스의 특성을 대치하거나 확장할 수 있다. 상속은 클래스 간의 'is a' 관계를 모델링 메뚜기  곤충  동물  생물 © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 76

상속 - 용어 이전 클래스 : 기본 클래스(base class) 확장된 클래스 : 파생 클래스(derived class) 혹은, 부모 클래스(parent class), 슈퍼 클래스(superclass) 확장된 클래스 : 파생 클래스(derived class) 혹은, 자식 클래스(child class), 서브 클래스(subclass) © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 77

상속 : 문법과 표기 // Existing class class Base { }; // Derived class class Derived : Base Inheritance Class Diagram Base Class Derived Class See pr11-20.cpp and inheritance.h © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 78

상속 - 멤버 class Parent { int a; int a; void bf(); void bf(); }; class Child : Parent int c; void df(); 부모 객체의 멤버 int a; void bf(); 자식 객체의 멤버 int c; void df(); © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 79

상속 예 Person Student Faculty © 2006 Pearson Education. //Global constants used for printing enumerated //types const string dName[] = { "Archeology", "Biology", "Computer Science" }; const string cName[] = { "Freshman", "Sophomore", "Junior", "Senior" int main() { //create a Faculty object Faculty prof; //use a Person member function prof.setName("Indiana Jones"); //use a Faculty member function prof.setDepartment(ARCHEOLOGY); cout << "Professor " << prof.getName() << " teaches in the " << "Department of "; //get department as an enumerated type Discipline dept = prof.getDepartment(); //print out the department in string form cout << dName[dept] << endl; return 0; } Person Student Faculty © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 80

11.11 보호 멤버와 클래스 접근 보호 멤버 접근 명세: protected 로 설정된 클래스 멤버는 같은 클래스의 멤버 함수 뿐 아니라 파생 클래스의 멤버 함수에 의해 접근이 가능하다. 파생 클래스의 멤버 함수에 의해 접근 가능하다는 점만 제외하고는 비공개 멤버와 같다. See inheritance1.h, inheritance1.cpp, pr11-21.cpp © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 81

기본 클래스 접근 명세 기본 클래스 접근 명세 : 기본 클래스의 private, protected, public 멤버들이 파생 클래스에 의해 어떤 방법으로 접근되는지를 결정한다. © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 82

기본 클래스 접근 세가지 상속 모델(기본 클래스 접근 모드) : - 공개 상속 class Child : public Parent { }; - 보호 상속 class Child : protected Parent{ }; - 비공개 상속 class Child : private Parent{ }; © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 83

기본 클래스 접근 vs. 멤버 접근 명세 기본 클래스 접근은 멤버 접근 명세와 같지 않다: 기본 클래스 접근: 상속된 멤버에 대한 접근을 결정 멤버 접근 명세: 클래스 내에 정의된 멤버의 접근을 결정 © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 84

멤버 접근 명세 private, protected, public 키워드를 사용한 명세 class MyClass { private: int a; protected: int b; void fun(); public: void fun2(); }; © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 85

기본 클래스 접근 명세 class Child : public Parent protected: int a; public: { protected: int a; public: Child(); }; base access member access © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 86

기본 클래스 접근 명세 public – 파생 클래스의 객체는 기본 클래스의 객체로 취급된다 (not vice-versa) protected – public 보다는 약간의 제약을 가지지만 부모의 상세 사항 중 일부를 파생 클래스에서 알 수 있게 한다. private –파생 클래스의 객체가 기본 클래스의 객체로 취급되는 것을 방지한다. © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 87

appear in derived class 기본 접근의 효과 How base class members appear in derived class 기본 클래스 멤버 private: x protected: y public: z private base class x inaccessible private: y private: z protected base class private: x protected: y public: z x inaccessible protected: y protected: z public base class private: x protected: y public: z x inaccessible protected: y public: z © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 88

보호 멤버 사용 예 © 2006 Pearson Education. enum Discipline { ARCHEOLOGY, BIOLOGY, COMPUTER_SCIENCE }; enum Classification { Freshman, Sophomore, Junior, Senior class Person{ protected: string name; public: Person() { setName("");} Person(string pName) { setName(pName);} void setName(string pName) { name = pName; } string getName() { return name; } class Student:public Person { private: Discipline major; Person *advisor; //constructor Student(string sname, Discipline d, Person *adv); void setMajor(Discipline d) { major = d; } Discipline getMajor(){return major; } void setAdvisor(Person *p){advisor = p;} Person *getAdvisor() { return advisor; } class Faculty:public Person { private: Discipline department; public: //constructor Faculty(string fname, Discipline d) //access the protected member name = fname; department = d; } void setDepartment(Discipline d) { department = d; } Discipline getDepartment( ) { return department; } }; © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 89

11.12 생성자, 소멸자 그리고 상속 기본 클래스의 모든 멤버를 상속함으로써 파생 클래스의 객체는 기본 클래스 객체를 포함한다. 파생 클래스의 생성자는 기본 클래스 객체를 초기화하기 위해 어떤 기본 클래스 생성자를 사용해야 하는 지를 규정할 수 있다. © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 90

호출 순서 파생 클래스의 객체가 생성될 때, 기본 클래스의 생성자가 먼저 실행되고 이러서 파생 클래스의 생성자가 호출된다. 파생 클래스의 객체가 소멸될 때, 파생 클래스의 소멸자가 먼저 호출되고 이어서 기본 클래스의 소멸자가 호출된다. See pr11-22.cpp © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 91

호출 순서 int main() { UnderGrad u1; ... return 0; }// end main // Student – base class // UnderGrad – derived class // Both have constructors, destructors int main() { UnderGrad u1; ... return 0; }// end main Execute Student constructor, then execute UnderGrad constructor See pr11-22.cpp Execute UnderGrad destructor, then execute Student destructor © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 92

기본 클래스 생성자에게 인수 전달하기 여러 기본 클래스 생성자를 호출할 것인가를 선택 파생 클래스의 생성자 정의에서 기본 클래스 생성자의 인자를 기술 인라인 생성자에서 사용 가능 기본 클래스가 디폴트 생성자를 갖지 않으면 반드시 인수를 전달하여야 한다. © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 93

기본 클래스 생성자에게 인수 전달하기 class Parent { int x, y; public: Parent(int,int); }; class Child : public Parent { int z public: Child(int a): Parent(a,a*a) {z = a;} See inheritance2.h, inheritance2.cpp, pr11-23.cpp © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 94

11.13 기본 클래스 함수의 오버라이드 오버라이딩(Overriding): 파생 클래스의 함수가 기본 클래스의 함수와 같은 함수 이름과 매개변수 목록을 가지게 재정의 파생 클래스에서 다른 동작을 가지게 기본 클래스의 함수를 대치한다. 과적과는 다르다 – 함수 과적의 경우 매개 변수 목록이 달라야 한다. See inheritance3.h, inheritance3.cpp, pr11-24.cpp © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 95

오버라이드된 기본 클래스 멤버함수에 접근 함수가 오버라이드될 때, 파생 클래스의 모든 객체는 오버라이드 함수를 사용한다. 오브라이드된 함수에 접근이 필요한 경우에는 영역 연산자(::)를 기본 클래스 이름과 함수 이름 사이에 사용한다: Student::getName(); See inheritance3.h, inheritance3.cpp, pr11-24.cpp © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 96

class TFaculty : public Faculty { private: string title; public: TFaculty(string fname, Discipline d, string title) : Faculty(fname, d) setTitle(title); } void setTitle(string title) this->title = title; //override getName() string getName( ) return title + " " + Person::getName(); }; © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 97

const string dName[] = { // 프로그램 11-23 Tfaculty p. 713 "Archeology", "Biology", "Computer Science" }; const string cName[] = { "Freshman", "Sophomore", "Junior", "Senior" int main() { // New constructor allows specification of title TFaculty prof("Indiana Jones", ARCHEOLOGY, "Dr."); Student st("Sean Bolster", ARCHEOLOGY, &prof); // Use the new TFaculty version of getName cout << prof.getName() << " teaches " << dName[prof.getDepartment()] << "." << endl; // This call uses the Person version of getName Person *pAdvisor = st.getAdvisor(); cout << st.getName() <<"\'s advisor is " << pAdvisor->getName() << "."; return 0; } © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 98

Starting Out with C++: Early Objects 5th Edition Chapter 11 More About Classes and Object-Oriented Programming Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved