Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Starting Out with C++: Early Objects 5th Edition"— Presentation transcript:

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

2 목 차 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

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

4 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

5 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

6 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

7 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; // } // this->x © 2006 Pearson Education. All Rights Reserved Chapter 11 Starting Out with C++: Early Objects 5/e slide 7

8 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

9 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

10 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

11 정적 멤버 변수 키워드 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

12 정적 멤버 변수 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

13 정적 멤버 변수 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

14 정적 멤버 변수 사용 #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

15 정적 멤버 변수 사용 © 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

16 정적 멤버 함수 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

17 정적 멤버 함수 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

18 정적 멤버 함수 사용 // 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

19 정적 멤버 함수 사용 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

20 정적 멤버 함수 사용 © 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

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

22 프렌드 함수 선언 외부 함수: 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

23 프렌드 함수 선언 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

24 프렌드 클래스 선언 전체 클래스가 클래스의 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

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

26 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

27 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

28 복사 생성자 객체가 동적 기억장소에 대한 포인터를 가질 때 문제가 발생한다: 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

29 디폴터 복사 생성자는 기억장소 공유 문제를 야기
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

30 동적 기억장소 공유에 따른 문제점(디폴터 복사 생성자)
다른 객체에 의해 아직 사용 중인 기억장소를 한 객체의 소멸자에 의해 삭제한다. 한 객체에 대한 기억장소의 수정이 기억장소를 공유하고 있는 다른 객체에 영향을 미친다. 주의 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

31 동적 기억장소 공유에 따른 문제점 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

32 동적 기억장소 공유에 따른 문제점 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

33 동적 기억장소 공유에 따른 문제점 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

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

35 프로그래머 정의 복사 생성자 복사 생성자는 기억장소 공유에 의해 야기되는 문제를 해결할 수 있다.
새로운 객체의 동적 멤버 자료를 위해 독립적인 기억장소를 할당한다. 새로운 객체의 포인터가 독립된 동적 기억장소를 가리키게 한다. 원 객체에서 새 객체로 포인터가 아니라 자료를 복사하게 한다. 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

36 복사 생성자 예 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

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

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

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

40 연산자 과적 :인스턴스 멤버 인스턴스 멤버로 과적된 이진 연산자는 오른쪽의 피연산자를 나타내는 하나의 매개변수 만을 요구한다:
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

41 연산자 과적 :인스턴스 멤버 과적된 이진 연산자의 왼쪽 피연산자는 호출한 객체이다.
묵시적인 왼쪽 매개변수는 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

42 과적된 연산자의 호출하기 연산자는 멤버 함수 형태로 호출될 수 있다: 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

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

44 배정연산자 과적 배정연산자 과적(멤버 함수): { 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

45 배정연산자 과적 클래스의 객체를 반환: 배정 연산자 호출: { *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

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

47 연산자 과적 유형 ++, -- 연산자는 전위/후위 표기에 따라 서로 다른 방법으로 과적된다.
과적된 관계 연산자는 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

48 연산자 과적 예 © 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

49 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

50 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

51 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

52 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

53 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

54 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

55 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

56 [] 연산자 과적 첨자 검사를 수행할 수 있는 배열과 같은 클래스를 생성
과적된 []는 객체의 참조를 반환한다.(객체 자신이 아니라) 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

57 [] 연산자 과적 예 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

58 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

59 //***********************************************************
// 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

60 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

61 //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

62 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

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

64 변환 연산자의 예 클래스 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

65 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

66 변환 생성자 예 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

67 변환 생성자 사용 변환 생성자는 매개변수로 전달된 값으로부터 객체를 생성하기 위해 컴파일러에 의해 자동으로 호출된다:
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

68 변환 생성자 사용 변환 생성자는 매개변수로 그 클래스 형을 취하는 함수에게 다른 자료형의 매개변수를 취할 수 있게한다:
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

69 변환 생성자 사용 예 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

70 //*******************************************
// 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

71 //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

72 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

73 객체 결합 예 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

74 객체 결합 예 © 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

75 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

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

77 상속 - 용어 이전 클래스 : 기본 클래스(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

78 상속 : 문법과 표기 // 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

79 상속 - 멤버 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

80 상속 예 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

81 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

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

83 기본 클래스 접근 세가지 상속 모델(기본 클래스 접근 모드) : - 공개 상속
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

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

85 멤버 접근 명세 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

86 기본 클래스 접근 명세 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

87 기본 클래스 접근 명세 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

88 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

89 보호 멤버 사용 예 © 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

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

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

92 호출 순서 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

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

94 기본 클래스 생성자에게 인수 전달하기 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

95 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

96 오버라이드된 기본 클래스 멤버함수에 접근 함수가 오버라이드될 때, 파생 클래스의 모든 객체는 오버라이드 함수를 사용한다.
오브라이드된 함수에 접근이 필요한 경우에는 영역 연산자(::)를 기본 클래스 이름과 함수 이름 사이에 사용한다: 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

97 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

98 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

99 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


Download ppt "Starting Out with C++: Early Objects 5th Edition"

Similar presentations


Ads by Google