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

Slides:



Advertisements
Similar presentations
3. 메소드와 변수 SCJP 자격증 프로젝트 발표자 : 최선웅. 1. 메 소 드 개 념 2. 메 소 드 양 식 3. 메 소 드 변 수 4. 메 소 드 예 제 5. 참 고 문 헌 / 자 료 목 차.
Advertisements

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 실 습실 습 2.
1 08 배열. 한국대학교 객체지향연구소 2 C 로 배우는 프로그래밍 기초 2 nd Edition 배열  동일한 자료유형의 여러 변수를 일괄 선언  연속적인 항목들이 동일한 크기로 메모리에 저장되는 구조  동일한 자료 유형이 여러 개 필요한 경우에 이용할 수 있는.
01_ 가상 함수를 사용한 다형성의 구현 02_ 오버라이딩
ㅎㅎ 구조체 구조체 사용하기 함수 매개변수로서의 구조체 구조체 포인터와 레퍼런스 구조체 배열.
ㅎㅎ 구조체 C++ 프로그래밍 기초 : 객체지향의 시작 구조체 사용하기 함수 매개변수로서의 구조체 구조체 포인터와 레퍼런스
ㅎㅎ C++ 프로그래밍의 첫 걸음 C++로 프로그래밍한다는 것의 의미 세상에서 가장 간단한 C++ 프로그램
2장. 프로그램의 기본 구성. 2장. 프로그램의 기본 구성 2-1"Hello, World!" 들여다 보기 /* Hello.c */ #include int main(void) { printf("Hello, World! \n"); return 0;
클래스 class, 객체 object 생성자 constructor 접근 access 제어 이벤트 event 처리.
최윤정 Java 프로그래밍 클래스 상속 최윤정
9장. C 언어의 핵심! 함수. 9장. C 언어의 핵심! 함수 9-1 함수의 정의와 선언 main 함수 다시 보기 : 함수의 기본 형태 { } 그림 9-1.
Java로 배우는 디자인패턴 입문 Chapter 5. Singleton 단 하나의 인스턴스
#include <stdio.h> int main(void) { float radius; // 원의 반지름
제 9 장 구조체와 공용체.
Starting Out with C++: Early Objects 5th Edition
7장 배열 ②.
3장. 변수와 연산자. 3장. 변수와 연산자 3-1 연산자, 덧셈 연산자 연산자란 무엇인가? 연산을 요구할 때 사용되는 기호 ex : +, -, *, / 3-1 연산자, 덧셈 연산자 연산자란 무엇인가? 연산을 요구할 때 사용되는 기호 ex : +, -, *, /
윤성우의 열혈 C 프로그래밍 윤성우 저 열혈강의 C 프로그래밍 개정판 Chapter 12. 포인터의 이해.
제 6장. 생성자와 소멸자 학기 프로그래밍언어및실습 (C++).
제 3장. C보다 나은 C++ II.
1. C++ 시작하기.
11장. 포인터 01_ 포인터의 기본 02_ 포인터와 Const.
SqlParameter 클래스 선문 비트 18기 발표자 : 박성한.
컴퓨터 프로그래밍 기초 #02 : printf(), scanf()
정적 멤버 변수/정적 멤버 함수 - friend 함수/클래스 template
자바 5.0 프로그래밍.
제4장 클래스와 객체 객체 지향 기법을 이해한다. 클래스를 작성할 수 있다. 클래스에서 객체를 생성할 수 있다.
23장. 구조체와 사용자 정의 자료형 2.
컴퓨터 프로그래밍 실습 #6 제 4 장 클래스 작성.
14. 예외처리.
11장. 1차원 배열.
C#.
13. 연산자 오버로딩.
C 프로그래밍 C언어 (CSE2035) (Chap11. Derived types-enumerated, structure, and union) (1-1) Sungwook Kim Sogang University Seoul, Korea Tel:
7장 인터페이스와 추상 클래스.
Method & library.
JA A V W. 03.
사용자 함수 사용하기 함수 함수 정의 프로그램에서 특정한 기능을 수행하도록 만든 하나의 단위 작업
어서와 C언어는 처음이지 제14장.
3장 상수 변수 기본 자료형 키워드와 식별자 상수와 변수 기본 자료형 형변환 자료형의 재정의.
HTTP 프로토콜의 요청과 응답 동작을 이해한다. 서블릿 및 JSP 를 알아보고 역할을 이해한다.
3장. 변수와 연산자 교안 : 전자정보통신 홈페이지 / 커뮤니티/ 학술세미나
Lesson 2. 기본 데이터형.
Term Projects 다음에 주어진 2개중에서 한 개를 선택하여 문제를 해결하시오. 기한: 중간 보고서: 5/30 (5)
Chapter6 : JVM과 메모리 6.1 JVM의 구조와 메모리 모델 6.2 프로그램 실행과 메모리 6.3 객체생성과 메모리
컴퓨터 프로그래밍 기초 - 10th : 포인터 및 구조체 -
컴퓨터 프로그래밍 기초 - 8th : 함수와 변수 / 배열 -
5장 선택제어문 if 선택문 switch-case 선택문 다양한 프로그램 작성 조건 연산자.
Chapter 08. 함수.
Fucntion 요약.
12. 상속 : 고급.
객체기반 SW설계 팀활동지 4.
클래스 : 기능 CHAPTER 7 Section 1 생성자(Constructor)
중복 멤버의 처리 조 병 규 한 국 교 통 대 학 교 SQ Lab..
제 8장. 클래스의 활용 학기 프로그래밍언어및실습 (C++).
3. 모듈 (5장. 모듈).
서브클래스 조 병 규 한 국 교 통 대 학 교 SQ Lab..
컴퓨터 프로그래밍 기초 - 9th : 배열 / 포인터 -
구조체(struct)와 공용체(union)
Numerical Analysis Programming using NRs
Chapter 11 구조체.
Static과 const 선언 조 병 규 한 국 교 통 대 학 교 SQ Lab..
제 4 장 Record.
윤성우의 열혈 C++ 프로그래밍 윤성우 저 열혈강의 C++ 프로그래밍 개정판 Chapter 05. 복사 생성자.
프로그래밍 개론 Ⅰ-실습 2장 데이터와 식①.
1. 지역변수와 전역변수 2. auto, register 3. static,extern 4. 도움말 사용법
어서와 C언어는 처음이지 제21장.
상속 (Inheritance) private 전용부분 전용부분 공용부분 공용부분 public 기본 클래스
7 생성자 함수.
6 객체.
Presentation transcript:

Starting Out with C++: Early Objects 5th Edition Chapter 7 클래스와 객체에 대한 소개 Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved

목 차 7.1 자료를 조합해서 구조체로 만들기 7.2 구조체 멤버에 접근하기 7.3 구조체 초기화 7.4 중첩 구조체 7.1 자료를 조합해서 구조체로 만들기 7.2 구조체 멤버에 접근하기 7.3 구조체 초기화 7.4 중첩 구조체 7.5 함수 인자로서의 구조체 7.6 함수로부터 구조체의 반환 ------------------------------------------- 7.7 공용체 7.8 추상 자료형 7.9 객체 지향 프로그래밍 © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 2

목 차(계속) 7.10 클래스의 소개 7.11 객체의 소개 7.12 멤버 함수 정의 7.13 설계 고려사항 7.10 클래스의 소개 7.11 객체의 소개 7.12 멤버 함수 정의 7.13 설계 고려사항 7.14 클래스의 생성자 사용하기 7.15 생성자의 과적 7.16 소멸자 7.17 입력 검증 객체 7.18 private 멤버 함수의 사용 © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 3

7.1 자료를 조합해서 구조체로 만들기 구조체(Structure): 여러 개의 변수를 단일 요소로 그룹 짓게 한다. 구조체 선언 형식: struct structure name { type1 field1; type2 field2; … typen fieldn; }; © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 4

구조체 선언 예 struct Student { int studentID; string name; short year; double gpa; // grade point average }; 구조체 태그 구조체 멤버 Notice the required ; © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 5

구조체 선언 유의사항 구조체 이름은 일반적으로 대문자로 시작한다. Student 같은 자료형인 멤버들은 컴마에 의해 구분하여 선언될 수 있다. string name, address; © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 6

구조체 변수 정의 구조체 선언은 메모리를 할당하거나 변수를 생성하지 않는다. 구조체 변수를 정의하려면 구조체 태그를 자료형으로 사용한다. Student s1; studentID name year gpa s1 © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 7

7.2 구조체 멤버에 접근하기 도트 연산자(.)를 사용하여 구조체 변수의 멤버에 접근한다. 7.2 구조체 멤버에 접근하기 도트 연산자(.)를 사용하여 구조체 변수의 멤버에 접근한다. getline(cin, s1.name); cin >> s1.studentID; s1.gpa = 3.75; 멤버 변수는 이들 자료형 사용에 적절한 어떠한 곳에서도 사용 가능하다. © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 8

구조체 멤버 출력 구조체 변수의 내용을 출력하기 위해서는 도트 연산자를 사용하여 각 필드를 각각 출력하여야 한다. Wrong: cout << s1; // won’t work! Correct: cout << s1.studentID << endl; cout << s1.name << endl; cout << s1.year << endl; cout << s1.gpa; See pr7-01.cpp and pr7-02.cpp © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 9

7.3 구조체 초기화 구조체 선언 시에는 메모리가 아직 할당되지 않았기 때문에 멤버를 초기화할 수 없다. 주의! struct Student // Illegal { // initialization int studentID = 1145; string name = "Alex"; short year = 1; float gpa = 2.95; }; 주의! © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 10

구조체 초기화 구조체 멤버는 구조체 변수가 생성될 때 초기화할 수 있다. 구조체 변수의 멤버 초기화 방법 초기화 목록(initialization list) 생성자(constructor) © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 11

초기화 목록의 사용(구조체 초기화) 초기화 목록(initialization list )은 중괄호 { }에 둘러싸인 컴마에 의해 구분된, 순서화 자료값으로 구조체 멤버의 초기값을 제공한다. Dimensions box = {12, 6, 3}; // initialization list // with 3 values © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 12

초기화 목록의 사용 목록의 순서가 중요(First value  first data member, second value  second data member, etc.을 초기화 한다.) 초기화 목록에는 상수, 변수, 수식이 올 수 있다. {12, W, L/W + 1} // initialization list // with 3 items © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 13

초기화 목록의 사용 예 struct Dimensions { int length, width, height; }; 구조체 선언 구조체 변수 struct Dimensions { int length, width, height; }; Dimensions box = {12,6,3}; box length 12 width 6 height 3 © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 14

부분적인 초기화 멤버의 일부만 초기화할 수도 있지만 중간의 멤버를 건너 뛸 수는 없다. Dimensions box1 = {12,6}; //OK Dimensions box2 = {12,,3}; //illegal 주의! © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 15

생성자 사용(구조체 초기화) 생성자(constructor )는 구조체 멤버인 특별한 함수이다. 구조체 선언 내부에서 주로 작성된다. 구조체 자료 멤버의 초기화 목적으로 사용된다. © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 16

생성자 사용(구조체 초기화) 생성자는 정규 함수처럼 호출되는 대신에 구조체 변수가 생성될 때 자동으로 실행된다. 생성자 이름은 구조체 이름(태그)과 같아야 한다. 생성자에는 반환형이 없다. © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 17

생성자를 가진 구조체 struct Dimensions { int length, width, height; // 생성자 Dimensions(int L, int W, int H) {length = L; width = W; height = H;} }; © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 18

생성자를 가진 구조체 struct Employee { string name; // 종업원 이름         {                 string name;            // 종업원 이름                 int vacationDays,    // 년간 휴가 일수                     daysUsed;          // 올해 사용한 휴가 일수                 Employee()              // 생성자                 { name = "";                   vacationDays = 10;                   daysUsed = 0;                 }         }; Employee emp1, emp2; © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 19

인자를 받는 생성자 구조체 변수를 생성하고, 변수 이름 다음에 인자 목록을 준다. 예: Dimensions box3(12, 6, 3); © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 20

인자를 받는 생성자 예 struct PopInfo { string name; // 도시명         {                 string name;            // 도시명                 long population;         // 도시의 인구                 PopInfo(string n, long p) // 2 개의 매개변수를 가지는 생성자                 { name = n;                 population = p;                 }         }; 이제 PopInfo 변수는 다음과 같이 생성되고 초기화될 수 있다.         PopInfo city1("Aurora ", 162184);         PopInfo city2(" Naperville", 137894); © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 21

인자를 받는 생성자 예 (디폴트 인자) 생성자에 디폴트 인자를 허용 struct Dimensions { int length, width, height; // Constructor Dimensions(int L=1, int W=1, int H=1) {length = L; width = W; height = H;} }; © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 22

Omit () when no arguments are used 디폴트 인자 사용 예 //Create a box with all dimensions given Dimensions box4(12, 6, 3); //Create a box using default value 1 for //height Dimensions box5(12, 6); //Create a box using all default values Dimensions box6; See pr7-03.cpp Omit () when no arguments are used © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 23

7.4 중첩 구조체 구조체는 다른 구조체를 멤버로 가질 수 있다. { string name, address, city; }; struct PersonInfo { string name, address, city; }; struct Student { int studentID; PersonInfo pData; short year; double gpa; © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 24

중첩 구조체의 멤버 주의! 중첩 구조체의 필드에 접근하기 위해 도트 연산자를 여러 번 사용한다. Student s5; s5.pData.name = "Joanne"; s5.pData.city = "Tulsa"; 모든 구조체 사용에 있어서 멤버를 접근하려면 구조체 태그 이름이 아니라 멤버 이름을 사용해야 한다. Cout << s5.name // 틀림 Cout << s5. PersonInfo.name //틀림 주의! See pr7-04.cpp © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 25

7.5 함수 인자로서의 구조체 함수에게 구조체 변수의 멤버를 전달할 수 있다. 함수에게 구조체 변수 전체를 전달할 수 있다. computeGPA(s1.gpa); 함수에게 구조체 변수 전체를 전달할 수 있다. showData(s5); 함수가 구조체 변수의 내용을 변경하기 원하면 참조 매개변수를 사용할 수 있다. © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 26

// 이름이 Rectangle인 구조체를 선언한다. struct Rectangle { double length, width, 개별 멤버를 함수 인자로 사용         // 이름이 Rectangle인 구조체를 선언한다.         struct Rectangle         {          double length,                 width,                 area;         };         // Rectangle 변수를 정의한다.         Rectangle box;         // 2 개의 double 매개변수를 가지는 함수를 정의한다.         double multiply(double x, double y)                 return x * y;         } 다음 함수 호출은 box.length를 x에 box.width를 y에 전달한다. 반환값은 box.area에 저장된다. box.area = multiply(box.length, box.width); © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 27

가끔은 개별 멤버 대신에 구조체 전체를 함수에게 전달하는 것이 편리하다. 다음 구조체 전체를 함수 인자로 사용하기 가끔은 개별 멤버 대신에 구조체 전체를 함수에게 전달하는 것이 편리하다. 다음 함수 정의는 매개변수로 Rectangle 구조체 변수를 사용한다.         void showRect(Rectangle r)         {                 cout << r.length << endl;                 cout << r.width << endl;                 cout << r.area << endl;         } 다음 함수 호출은 box 변수 전체를 r에 전달한다.         showRect(box); showRect 함수 내에서 r의 멤버는 box 멤버에 대한 복사본을 가진다. 그림 7-4는 이를 보여준다. © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 28

그림 7-4 복사본 © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 29

참조에 의한 전달(구조체) 함수가 원래 인자의 멤버에 대해 접근 권한을 가지기를 원하는 경우 프로그램 7-5에서 InvItem 구조체 선언이 getItem과 showItem 함수의 원형 또는 함수 정의 이전에 나타나는 것에 주목하자. 그 이유는 두 함수가 InvItem 구조체 변수를 매개변수로 사용하기 때문이다.  컴파일러는 이러한 구조체 자료형에 대한 변수 정의를 만나기 전에 InvItem이 무엇인 지를 반드시 알아야 한다. © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 30

프로그램 7-5  1 // 이 프로그램은 함수의 인자로 구조체 전체를 전달할 때  2 // 값에 의한 전달과 참조에 의한 전달 방법을 사용하는 것을 보여준다.  3 #include <iostream>  4 #include <iomanip>  5 #include <string>  6 using namespace std;  7  8 struct InvItem  9 { 10     int partNum;             // 부품 번호 11     string description;        // 품목 12     int onHand;              // 재고 13     double price;            // 단위 당 가격 14 }; 15 16 // Function prototypes 17 void getItem(InvItem&);      // 전체 InvItem 구조체가  getItem 함수에 18                             // 전달된다. 참조에 의해 전달되기 때문에 19                             // getItem이 원 구조체 변수에 새 자료를 20                             // 넣을 수 있다. 21                             // &에 주목하자. 22 23 void showItem(InvItem);      // 전체 InvItem 구조체가  showItem 함수에 24                             // 전달된다. 값에 의해 전달되기 때문에 25                             // showItem은 자료의 복사본만 필요하고, 26                             // 원 구조체 변수를 수정할 필요가 27                             // 없다. © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 31

cin.ignore() 28 int main() 29 { 30     InvItem part;            // 변수 part를 InvItem 구조체로 31                              // 정의한다. 32     getItem (part); 33     showItem(part); 34     return 0; 35 } 36 37 //******************************************************************* 38 //                           getItem                              * 39 //  이 함수는 사용자의 데이터를 입력 받아 참조에 의해               * 40 //  전달된 InvItem 구조체 변수의 멤버에 저장한다.                   * 41 // ****************************************************************** 42 void getItem(InvItem &piece)  // 참조 매개변수인 &에 43 {                            // 주목하자. 44     cout << "Enter the part number: "; 45     cin >> piece.partNum; 46     cout << "Enter the part description: "; 47     cin.get();                // 입력 버퍼에 남아 있는 '\n'을 48                              // 지나 이동한다. 49     getline(cin, piece.description); 50     cout << "Enter the quantity on hand: "; 51     cin >> piece.onHand; 52     cout << "Enter the unit price: "; 53     cin >> piece.price; 54 } 55 cin.ignore() © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 32

58 // 이 함수는 전달된 InvItem 구조체 변수의 멤버에 저장되어 있는 * 59 // 자료를 출력한다. * 56 //******************************************************************* 57 //                           showItem                           * 58 // 이 함수는 전달된 InvItem 구조체 변수의 멤버에 저장되어 있는      * 59 // 자료를 출력한다.                                               * 60 // ****************************************************************** 61 void showItem(InvItem piece) 62 { 63     cout << fixed << showpoint << setprecision(2) << endl;; 64     cout << "Part Number : " << piece.partNum << endl; 65     cout << "Description : " << piece.description << endl; 66     cout << "Units On Hand: " << piece.onHand << endl; 67     cout << "Price : $" << piece.price << endl; 68 } 프로그램 출력(입력 예는 굵은 글씨) Enter the part number: 800[Enter] Enter the part description: Screwdriver[Enter] Enter the quantity on hand: 135[Enter] Enter the unit price: 1.25[Enter] Part Number : 800 Description : Screwdriver Units On Hand: 135 Price : $1.25 © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 33

상수 참조에 의한 전달(구조체) void showItem (const InvItem&); // 함수 원형  // 함수 원형  void showItem (const InvItem &piece)     // 함수 헤드 © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 34

구조체 전달 시 유의 사항 구조체에 대한 값에 의한 전달 : 프로그램 실행 속도 저하 메모리 낭비 초래 참조에 의한 전달 : 속도를 높일 수 있다. 함수 내에서 구조체 내의 자료를 변경할 수 있다. 변경하기를 원하지 않는 구조체 자료를 보호하는 동시에 실행 시간과 공간을 줄이기 원할 때  상수 참조 매개변수 사용!! void showData(const Student &s) // header See pr7-05.cpp © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 35

7.6 함수로부터 구조체의 반환 함수는 구조체를 반환할 수 있다. 함수는 지역 구조체를 정의하여야 한다 Student getStuData(); // 원형 s1 = getStuData(); // 호출 함수는 지역 구조체를 정의하여야 한다 내부적인 사용 return 문의 사용 © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 36

구조체의 반환 예 Student getStuData() { Student s; // local variable cin >> s.studentID; cin.ignore(); getline(cin, s.pData.name); getline(cin, s.pData.address); getline(cin, s.pData.city); cin >> s.year; cin >> s.gpa; return s; } See pr7-06.cpp © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 37

1 // 이 프로그램은 하나의 구조체를 반환하는 함수를 사용한다. 2 #include <iostream> 프로그램 7-6  1 // 이 프로그램은 하나의 구조체를 반환하는 함수를 사용한다.  2 #include <iostream>  3 #include <iomanip>  4 #include <cmath>    // pow 함수를 위해 필요하다.  5 using namespace std;  6  7 // Circle 구조체 선언  8 struct Circle  9 { 10     double radius; 11     double diameter; 12     double area; 13 }; 14 15 // 함수 원형 16 Circle getInfo(); 17 18 const double PI = 3.14159; 19 © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 38

22 Circle c1, c2; // 2 Circle 구조체 변수 정의 23 24 // circle 자료를 얻는다. 20 int main() 21 { 22     Circle c1, c2;   // 2 Circle 구조체 변수 정의 23 24     // circle 자료를 얻는다. 25     c1 = getInfo(); 26     c2 = getInfo(); 27 28     // circle의 면적을 계산한다. 29     c1.area = PI * pow(c1.radius, 2.0); 30     c2.area = PI * pow(c2.radius, 2.0); 31 32     // 결과 출력 33     cout << fixed << showpoint << setprecision(2); 34     cout << "\nThe radius and area of the circles are\n"; 35     cout << "Circle 1 -- Radius: " << setw(6) << c1.radius 36     << " Area: " << setw(6) << c1.area << endl; 37     cout << "Circle 2 -- Radius: " << setw(6) << c2.radius 38     << " Area: " << setw(6) << c2.area << endl; 39     if (c1.area == c2.area) 40             cout << "The two circles have the same area.\n\n"; 41 42     return 0; 43 } 44 © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 39

47 // 이 함수는 입력된 원의 지름과 계산된 원의 반지름을 수용하기 * 45 //************************************************************************** 46 //                           getInfo                          * 47 // 이 함수는 입력된 원의 지름과 계산된 원의 반지름을 수용하기   * 48 // 위해 round 라는 지역 circle 구조체 변수를 사용한다.           * 49 // round 변수는 호출한 함수에게                                * 50 // 반환된다.                                                  * 51 //*************************************************************************** 52 Circle getInfo()              // 함수 반환형이 Circle 구조체이다. 53 { 54     Circle round;           // 입력 자료를 보관하기 위한 지역 구조체 변수 55 56     cout << "Enter the diameter of a circle: "; 57     cin >> round.diameter; 58     round.radius = round.diameter / 2; 59     return round; 60 } 프로그램 출력(입력 예는 굵은 글씨) Enter the diameter of a circle: 2.0[Enter] Enter the diameter of a circle: 4.0[Enter] The radius and area of the circles are Circle 1 -- Radius: 1.00 Area: 3.14 Circle 2 -- Radius: 2.00 Area: 12.57 © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 40

7.7 공용체 공용체(union)는 구조체와 유사하지만, 키워드 union 그 외는 구조체와 같다. 7.7 공용체 공용체(union)는 구조체와 유사하지만, 모든 멤버가 단일 메모리 주소를 공유한다. (기억장소의 절약) 공용체의 한 멤버만이 한 시점에 사용될 수 있다. 키워드 union 그 외는 구조체와 같다. 구조체 변수와 같은 방법으로 정의되고 접근된다. © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 41

공용체 선언 예 union WageInfo { double hourlyRate; float annualSalary; }; union tag union members See pr7-07.cpp Notice the required ; © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 42

공용체(기억장소 구성) union PaySource { short hours; float sales; };         {                 short hours;                 float sales;         }; 공용체 변수는 다음과 같이 정의된다.         PaySource employee1; © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 43

© 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 44

프로그램 7-7  1 // 이 프로그램은 공용체 사용의 예를 보여준다.  2 #include <iostream>  3 #include <iomanip>  4 using namespace std;  5  6 union PaySource                     // 공용체를 선언한다.  7 {  8     short hours;                    // 두 변수가 같은 기억 공간을  9      float sales;                    // 공유한다. 10 }; 11 12 int main() 13 { 14     PaySource employee1;          // employee1은 PaySource 공용체이다. 15                                     // 종업원은 hours 또는 sales를 가질 수 16                                     // 있지만 동시에 둘 다 가질 수는 없다. 17 18     char hourlyType;                // 시간제이면 'y', 수수료이면 'n' 19     float payRate, grossPay; 20 21     cout << fixed << showpoint << setprecision(2); 22     cout << "This program calculates either hourly wages or " 23             << "sales commission.\n"; 24     cout << "Is this an hourly employee (y or n)? "; 25     cin >> hourlyType; 26 © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 45

27     if (hourlyType == 'y')           // 시간제 종업원이다. 28     { 29             cout << "What is the hourly pay rate? "; 30             cin >> payRate; 31             cout << "How many hours were worked? "; 32             cin >> employee1.hours; 33             grossPay = employee1.hours * payRate; 34             cout << "Gross pay: $" << grossPay << endl; 35     } 36     else                            // 수수료를 받는 종업원이다. 37     { 38             cout << "What are the total sales for this employee? "; 39             cin >> employee1.sales; 40             grossPay = employee1.sales * 0.10; 41             cout << "Gross pay: $" << grossPay << endl; 42     } 43     return 0; 44 } 프로그램 출력(입력 예는 굵은 글씨) This program calculates either hourly wages or sales commission. Is this an hourly employee (y or n)? y[Enter] What is the hourly pay rate? 20[Enter] How many hours were worked? 40[Enter] Gross pay: $800.00 Program Output with Other Example Input Shown in Bold Is this an hourly employee (y or n)? n[Enter] What are the total sales for this employee? 5000[Enter] Gross pay: $500.00 © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 46

익명 공용체(Anonymous Union) 태그가 없는 공용체: union { ... }; 태그가 없기 때문에 나중에 이 공용체 변수를 생성할 수 없다. 선언 시에 메모리를 할당한다. 도트 연산자 없이 멤버를 직접 사용한다. See pr7-08.cpp © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 47

1 // 이 프로그램은 익명 공용체 사용의 예를 보여준다. 2 #include <iostream> 프로그램 7-8  1 // 이 프로그램은 익명 공용체 사용의 예를 보여준다.  2 #include <iostream>  3 #include <iomanip>  4 using namespace std;  5  6 int main()  7 {  8     union                   // 익명 공용체를 선언한다.  9     { 10             short hours;    // 이 두 변수는 같은 기억장소를 11             float sales;     // 공유한다. 12     }; 13 14     char hourlyType;        // 시간제이면 'y', 수수료이면 'n' 15     float payRate, grossPay; 16 17     cout << fixed << showpoint << setprecision(2); 18     cout << "This program calculates either hourly wages or " 19     << "sales commission.\n"; 20     cout << "Is this an hourly employee (y or n)? "; 21     cin >> hourlyType; 22 © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 48

23 if (hourlyType == 'y') // 시간제 종업원이다. 24 { 24     { 25             cout << "What is the hourly pay rate? "; 26             cin >> payRate; 27             cout << "How many hours were worked? "; 28             cin >> hours;   // 익명 공용체 멤버 29             grossPay = hours * payRate; 30             cout << "Gross pay: $" << grossPay << endl; 31     } 32     else                    // 수수료를 받는 종업원이다. 33     { 34             cout << "What are the total sales for this employee? "; 35             cin >> sales;   // 익명 공용체 멤버 36             grossPay = sales * 0.10; 37             cout << "Gross pay: $" << grossPay << endl; 38     } 39     return 0; 40 } 프로그램 출력(입력 예는 굵은 글씨) This program calculates either hourly wages or sales commission. Is this an hourly employee (y or n)? n[Enter] What are the total sales for this employee? 12000[Enter] Gross pay: $1200.00 © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 49

7.8 추상 자료형 (ADT:Abstract Data type) 프로그래머 정의 자료형 저장될 수 있는 값(value) 그 값에 적용될 수 있는 연산(operation) 추상 자료형의 사용자는 구현에 관한 상세한 사항을 알 필요가 없다. how the data is stored or how the operations on it are carried out © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 50

추상화와 추상 자료형 추상화(Abstraction): 어떤 것에 대한 일반적인 모델이다. 추상화는 객체의 특정 인스턴스에 대한 구체적인 특성을 밝히지 않고 객체의 일반적인 특성만을 포함하는 것 Ex. 추상화 삼각형은 3변을 가진 다각형이다. 정삼각형, 직각 이등변 삼각형, 이등변 삼각형 Ex. © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 51

추상화와 추상 자료형 추상 자료형: 자료형이 가질 수 있는 값을 정의하고, 이들 자료 상에서  수행될 수 있는 연산을 정의하고, 또한 이들 연산을 수행하기 위한 함수를 정의한다. 얼음 제조기의 추상화 ADT IceDispenser (Water, Motor, Button )       : GetMeChilledWater( );  냉수를 주세요.       : GetMeCrushedIce( );    부순 얼음 을 주세요.       : GetMeCubeIce( );        각진 얼음을 주세요. © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 52

7.9 객체 지향 프로그래밍 절차형 프로그래밍(Procedural programming) 프로그램 내에서 발생하는 절차나 동작을 중심으로 하는 S/W 개발 방식 객체 지향 프로그래밍(Object-Oriented programming) 자료와 자료 상에 동작하는 함수에 기반한다. 객체는 추상화 자료(ADT)의 인스턴스이다. © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 53

절차형 프로그래밍 자료는 주로 변수나 구조체에 저장되며, 이들 자료에 연산을 수행하는 함수들과 결합된다.  자료와 함수는 분리된 개체 예 표 7-2 Rectangle을 정의하는 변수 변수 선언 설명 double width;    직사각형의 폭 double length;   직사각형의 길이 표 7-3 Rectangle을 사용하는 함수 함수 이름        설명 setData()        width와 length에 값을 저장한다. displayWidth()    직사각형의 폭을 출력한다. displayLength()   직사각형의 길이를 출력한다. displayArea()    직사각형의 면적을 출력한다. 요구되는 연산을 수행하는 함수에게 변수와 자료 구조가 전달된다. 절차형 프로그래밍은 함수에 중심을 둔다. © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 54

절차형 프로그래밍의 제약 과도한 전역 변수의 사용 프로그래머가 중대한 자료를 부주의하게 파괴 프로그램이 복잡한 함수 계층에 기반할 수 있다. 이해하고 유지하기 어렵다. 수정하고 확장하기 어렵다. 함수 간의 종속관계  함수 수정이 다른 함수에게 영향을 미친다. © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 55

객체 지향 프로그래밍 클래스(class): 구조체와 유사 관련 변수(멤버 자료: member data)와 그 자료 상에 동작하는 함수(멤버 함수: member functions)를 함께 묶는다. 클래스가 가질 수 있는 모든 인스턴스(instance)의 속성을 기술한다. 객체(object): 변수가 구조체의 인스턴스인 것처럼 객체는 클래스의 인스턴스이다. © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 56

객체 지향 프로그래밍 Circle 멤버 변수 double radius; 멤버 함수 void setRadius(double r) { radius = r; } double getArea() { return 3.14 * pow(radius, 2); } Circle  원의 면적을 계산할 때, 메시지를 객체에 전달한다. Circle c1; c1.setRadius(2.3); c1.getArea(); getArea는 Circle 객체의 멤버이기 때문에 객체의 모든 멤버 변수를 접근할 수 있다. 따라서 getArea 함수에게 radius를 전달할 필요가 없다. © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 57

객체 지향 프로그래밍(용어) 속성(attributes): 클래스의 멤버 자료 메소드(methods) 또는 행위(behaviors): 클래스의 멤버 함수 자료 은닉(data hiding): 객체의 멤버에 대한 접근을 제약 © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 58

공개 인터페이스 클래스 객체는 클래스의 외부로부터 공개 인터페이스(public interface)를 통하여 접근된다. 클래스 외부로부터 호출되는 멤버 함수 허용 모든 멤버 변수는 공개 함수를 통해서만 접근 가능 자료 파괴로부터 보호 © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 59

그림 7-7 © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 60

7.10 클래스의 소개 클래스 선언은 멤버 변수와 그 클래스의 객체가 가지는 멤버 함수를 기술한다. 객체 생성을 위한 패턴 기술 클래스 선언 형식: class className { declaration; }; 멤버 변수 멤버 함수 Notice the required ; © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 61

접근 지정자 클래스 멤버에 대한 접근을 제어한다. Public(공개): 클래스의 외부 함수에 의해 접근 가능 또는 Private(비공개): 클래스 멤버인 함수에 의해서만 호출 또는 접근 가능 © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 62

클래스 예 class Square { private: int side; public: void setSide(int s) 공개 비공개 class Square { private: int side; public: void setSide(int s) { side = s; } int getSide() { return side; } }; 접근 지정자 © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 63

접근 지정자 클래스 내에서 어떠한 순서로도 나열될 수 있다. 클래스 내에서 여러 번 나타날 수 있다. 디폴트로 private(구조체는 디폴트로 public임) © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 64

7.11 객체의 소개 객체(object)는 클래스의 인스턴스(instance)이다. 7.11 객체의 소개 객체(object)는 클래스의 인스턴스(instance)이다. 인스턴스화 : 구조체 변수와 같은 방법으로 정의된다. Square sq1, sq2; 객체 멤버 접근 : 도트 연산자(.)를 사용한 멤버 접근 sq1.setSide(5); cout << sq2.getSide(); 도트 연산자를 사용하여 private 멤버를 접근하면 컴파일러 오류 발생 See pr7-09.cpp © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 65

© 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 66

setRadius getArea radius 프로그램 7-9 1 // 이 프로그램은 단순 클래스의 사용을 보여준다.  1 // 이 프로그램은 단순 클래스의 사용을 보여준다.  2 #include <iostream>  3 #include <cmath>  4 using namespace std;  5  6 // Circle 클래스 선언  7 class Circle  8 { private:  9 double radius; 10 11 public: 12 void setRadius(double r) 13 { radius = r; } 14 15 double getArea() 16 { return 3.14 * pow(radius, 2); } 17 }; 18 setRadius getArea radius © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 67

21 Circle sphere1, // 2 Circle 객체 정의 22 sphere2; 23 19 int main() 20 { 21 Circle sphere1,              // 2 Circle 객체 정의 22 sphere2; 23 24 sphere1.setRadius(1);  // 이 문장은 sphere1의 반지름을 1로 설정한다. 25 sphere2.setRadius(2.5); // 이 문장은 sphere2의 반지름을 2.5로 설정한다. 26 27 cout << "The area of sphere1 is " << sphere1.getArea() << endl; 28 cout << "The area of sphere2 is " << sphere2.getArea() << endl; 29 return 0; 30 } 프로그램 출력 The area of sphere1 is 3.14 The area of sphere2 is 19.625 © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 68

7.12 멤버 함수 정의 멤버 함수는 클래스 선언의 일부이다. 클래스 선언 내부에 함수 정의를 두거나 7.12 멤버 함수 정의 멤버 함수는 클래스 선언의 일부이다. 클래스 선언 내부에 함수 정의를 두거나 또는 클래스 선언 내부에는 함수 원형만 두고 클래스 외부에서 함수를 정의할 수 있다. © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 69

멤버 함수 정의 (클래스 선언 내부) 인라인 함수(inline functions) : 클래스 선언 내부에서 정의된 멤버 함수 멤버 함수 정의 (클래스 선언 내부) 인라인 함수(inline functions) : 클래스 선언 내부에서 정의된 멤버 함수 아래와 같이 아주 짧은 함수만 인라인 함수로 선언하여야 한다. int getSide() { return side; } © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 70

인라인 함수 예 class Square { private: int side; public: void setSide(int s) { side = s; } int getSide() { return side; } }; inline functions © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 71

멤버 함수 정의 (클래스 선언 외부) 클래스 선언 외부에서 멤버 함수를 정의하려면 { return side; } 멤버 함수 정의 (클래스 선언 외부) 클래스 선언 외부에서 멤버 함수를 정의하려면 클래스 선언 시 함수 원형을 선언하라. 함수 정의에서는 함수 이름 앞에 클래스 이름과 유효 범위 식별 연산자(scope resolution operator ) “::” 가 오게 하라. int Square::getSide() { return side; } See pr7-10.cpp and pr7-11.cpp © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 72

프로그램 7-10  1 // 이 프로그램은 클래스 선언의 외부에 정의된 멤버 함수를 가진  2 // 클래스를 보여준다.  3 #include <iostream>  4 #include <cmath>  5 using namespace std;  6  7 // Circle 클래스 선언  8 class Circle  9 {  private: 10     double radius; 11 12    public: 13     void setRadius(double); 14     double getArea(); 15 }; 16 17 // 멤버 함수 구현 부분 18 19 //***************************************************************** 20 //                   Circle::setRadius                          * 21 // 이 함수는 매개변수에 전달된 인자를 비공개 멤버 변수            * 22 // radius에 복사한다.                                           * 23 //***************************************************************** 24 void Circle::setRadius(double r) 25 {   radius = r; 26 } 27 © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 73

28 //***************************************************************** 29 //                   Circle::getArea                            * 30 // 이 함수는  Circle 객체의 면적을 계산하고 반환한다.             * 31 // 이 함수는 멤버 변수 radius에 대해 이미 접근 권한을             * 32 // 가지기 때문에 어떠한 매개변수도 필요가 없다.                    * 33 //***************************************************************** 34 double Circle::getArea() 35 { return 3.14 * pow(radius, 2); 36 } 37 38 //***************************************************************** 39 //                           main                             * 40 //***************************************************************** 41 int main() 42 { 43     Circle sphere1,          // 2 Circle 객체를 정의한다. 44            sphere2; 45 46     sphere1.setRadius(1);    // sphere1의 radius를 1로 설정한다. 47     sphere2.setRadius(2.5);  // sphere2의 radius를 2.5로 설정한다. 48 49     cout << "The area of sphere1 is " << sphere1.getArea() << endl; 50     cout << "The area of sphere2 is " << sphere2.getArea() << endl; 51     return 0; 52 } 프로그램 출력은 프로그램 7-9와 동일하다. © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 74

set 함수, get 함수 사용 예 프로그램 7-11 1 // 이 프로그램은 Rectangle 클래스를 구현한다.  2 #include <iostream>  3 using namespace std;  4  5 // Rectangle 클래스 선언  6 class Rectangle  7 {  8     private:  9             double length; 10             double width; 11     public: 12             void setLength(double); 13             void setWidth(double); 14             double getLength(); 15             double getWidth(); 16             double getArea(); 17 }; 18 © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 75

Chapter 7 Starting Out with C++: Early Objects 5/e slide 76 19 // 멤버 함수 구현 부분 20 21 //******************************************************************* 22 //                   Rectangle::setLength                        * 23 // 이 함수는 멤버 변수 length의 값을 설정한다.                      * 24 // 함수에게 전달된 인자가 0보다 크거나 같으면 length에              * 25 // 복사되고, 음수이면 1.0이 length에 배정된다.                      * 26 //******************************************************************* 27 void Rectangle::setLength(double len) 28 { 29     if (len >= 0) 30             length = len; 31     else 32     {       length = 1.0; 33             cout << "Invalid length. Using a default value of 1.\n"; 34     } 35 } 36 37 //******************************************************************* 38 //                   Rectangle::setWidth                         * 39 //  이 함수는 멤버 변수 width의 값을 설정한다.                     * 40 // 함수에게 전달된 인자가 0보다 크거나 같으면 width에              * 41 // 복사되고, 음수이면 1.0이 width에 배정된다.                       * 42 //******************************************************************* 43 void Rectangle::setWidth(double w) 44 { 45     if (w >= 0) 46             width = w; 47     else 48     {       width = 1.0; 49     cout << "Invalid width. Using a default value of 1.\n"; 50     } 51 } 52 © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 76

53 //******************************************************************* 54 //                   Rectangle::getLength                        * 55 // 이 함수는 비공개 멤버 length의 값을 반환한다.                     * 56 //******************************************************************* 57 double Rectangle::getLength() 58 { 59     return length; 60 } 61 62 //******************************************************************* 63 //                   Rectangle::getWidth                         * 64 // 이 함수는 비공개 멤버 width의 값을 반환한다.                     * 65 //******************************************************************* 66 double Rectangle::getWidth() 67 { 68     return width; 69 } 70 71 //******************************************************************* 72 //                   Rectangle::getArea                          * 73 // 이 함수는 rectangle의 면적을 계산하고 반환하다.                  * 74 //******************************************************************* 75 double Rectangle::getArea() 76 { 77     return length * width; 78 } 79 © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 77

80 //******************************************************************* 81 //                           main                              * 82 //******************************************************************* 83 int main() 84 { 85     Rectangle box;          // Rectangle 객체를 선언한다. 86     double boxLength, boxWidth; 87 88     // box의 length와 width를 읽는다. 89     cout << "This program will calculate the area of a rectangle.\n"; 90     cout << "What is the length? "; 91     cin >> boxLength; 92     cout << "What is the width? "; 93     cin >> boxWidth; 94 95     // box의 치수를 설정하기 위해 멤버 함수를 호출한다. 96     box.setLength(boxLength); 97     box.setWidth(boxWidth); 98 99     // 출력할 box의 치수를 읽기 위해 멤버 함수를 호출한다. 100    cout << "\nHere is the rectangle's data:\n"; 101    cout << "Length: " << box.getLength() << endl; 102    cout << "Width : " << box.getWidth() << endl; 103    cout << "Area : " << box.getArea() << endl; 104    return 0; 105 } © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 78

This program will calculate the area of a rectangle. 프로그램 출력(입력 예는 굵은 글씨) This program will calculate the area of a rectangle. What is the length? 3[Enter] What is the width? -1[Enter] Invalid width. Using a default value of 1. Here is the rectangle's data: Length: 3 Width : 1 Area : 3 프로그램 출력(입력의 또 다른 예는 굵은 글씨) What is the length? 10.1[Enter] What is the width? 5[Enter] Length: 10.1 Width : 5 Area : 50.5 © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 79

인라인 함수 vs. 클래스 외부 멤버 함수: Tradeoffs 정규 함수가 호출되면 호출된 함수로 제어가 전달된다. 컴파일러는 호출에 대한 반환 주소 저장, 지역 변수에 대한 메모리 할당과 같은 일을 수행한다. 호출 시 인라인 함수에 대한 코드가 프로그램 내로 복사된다. 실행 프로그램의 크기가 크지지만 함수 호출에 따른 부담이 줄게 되어 실행 속도가 빨라진다. © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 80

7.13 설계 고려 사항(S/W 공학) 클래스 멤버 함수 내에서 cin과 cout의 사용을 피하는 것이 일반적으로 좋은 설계 방법으로 생각된다. 클래스가 입력과 출력을 수행하는 방법에 고정되지 않기를 원할 것이다. (프로그램 7-11, 7-12의 setLength 함수 참고) 예외, 메뉴를 출력하기 위해 설계된 클래스  클래스 내에서 입출력 수행 © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 81

설계 고려 사항 클래스 선언과 멤버 함수 정의 그리고 클래스를 사용하는 프로그램을 각각 분리된 파일에 작성하는 것이 좋은 설계 방법이다. © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 82

분리된 파일의 사용 클래스 선언  헤드 파일(클래스 명세 파일:class specification file) 파일이름 classname.h (예, Square.h) #include “Square.h” 멤버 함수 정의  클래스 구현 파일(class implementation file) 파일 이름 classname.cpp (예, Square.cpp) 클래스 명세 파일을 #include 하여야 한다. 클래스 사용 프로그램 #include 클래스 명세 파일 클래스 구현 파일과 링크되어야 한다. See pr7-12.cpp, rectangle.cpp, and rectangle.h © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 83

Rectangle 클래스 선언을 포함한다. 이 파일은 rectangle.cpp와 pr7-12.cpp에 의해 포함되어진다. rectangle.h Rectangle 클래스 선언을 포함한다. 이 파일은 rectangle.cpp와 pr7-12.cpp에 의해 포함되어진다. rectangle.cpp Rectangle 클래스 멤버 함수의 정의를 포함한다. 이 파일은 rectangle.obj 같은 오브젝트 파일을 생성하기 위해 컴파일된다. pr7-12.cpp 클래스를 사용하는 클라이언트 코드를 포함한다. 이 경우에 클라이언트 코드는 main 함수만으로 구성된다. 이 파일은 pr7-12.obj 같은 오브젝트 파일을 생성하기 위해 컴파일된다. 링크 rectangle.cpp와 pr7-12.cpp를 컴파일하여 생성된 두 오브젝트 파일이 실행 파일 pr7-12.exe를 만들기 위해 링크된다. © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 84

7.14 클래스의 생성자 사용하기 생성자  클래스의 멤버 자료를 초기화 반드시 public 멤버 함수 7.14 클래스의 생성자 사용하기 생성자  클래스의 멤버 자료를 초기화 반드시 public 멤버 함수 클래스의 이름과 같아야 한다. 반환형이 없어야 한다. 클래스의 객체가 생성될 때, 자동으로 호출된다. © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 85

디폴트 생성자 생성자(Constructor)는 임의 개수의 매개변수(없는 경우 포함)를 가질 수 있다. 디폴트 생성자(default constructor)는 인자를 갖지 않는 생성자이다. 매개변수가 없는 경우 모든 매개변수가 디폴트 값을 가지는 경우 © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 86

디폴트 생성자 예 class Square { private: int side; public: Square() // default { side = 1; } // constructor // Other member // functions go here }; Has no parameters © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 87

but it has a default value 디폴트 생성자 예 class Square { private: int side; public: Square(int s = 1) // default { side = s; } // constructor // Other member // functions go here }; Has parameter but it has a default value © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 88

생성자의 호출 클래스 객체에 대한 생성자 호출  구조체 변수의 생성자 호출과 같다. 디폴트 생성자를 사용하여 객체를 생성하기 위해서는 인자 목록과 ( ) 없이 사용 Square square1; 매개 변수를 가지는 생성자를 사용하여 객체를 생성하는 경우는 인자를 포함 Square square1(8); See pr7-13.cpp © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 89

7.15 생성자의 과적 클래스는 여러 개의 생성자를 가질 수 있다. 생성자가 과적될 때, 서로 다른 매개변수 목록을 가져야 한다. Square(); Square(int); 단지 하나의 디폴트 생성자만 허용된다. © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 90

멤버 함수 과적 어떠한 클래스 멤버 함수도 과적될 수 있다. void setSide(); void setSide(int); 반드시 고유한 매개변수 목록을 가져야 한다. See pr7-14.cpp and sale.h © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 91

        sale.h 내용         #ifndef SALE_H         #define SALE_H         // Sale 클래스 선언         class Sale         {         private:                 double taxRate;                 double total;                 void calcSale(double cost)                 { total = cost + (cost * taxRate); }         public:                 // 과세 매상을 다루는 2 개의 매개 변수를 가진 생성자                 Sale(double rate, double cost)                 { taxRate = rate; calcSale(cost); }                 // 면세 매상을 다루는 1 개 매개 변수를 가진 생성자                 Sale(double cost)                 { taxRate = 0.0; total = cost; }                 // 디폴트 생성자                 Sale()                 { taxRate = 0.0; total = 0.0; }                 double getTotal()                 { return total; }         };         #endif © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 92

프로그램 7-14  1 // 이 프로그램은 Sale 클래스를 사용한다. 이 파일은 하나의 프로젝트 내에   2 // sale.h와 sale.cpp 파일을 함께 결합하여야 한다.  3 #include <iostream>  4 #include <iomanip>  5 using namespace std;  6 #include "sale.h"  7  8 int main()  9 { 10 // 매상이 $24.95이고, 6% 세율을 가진 Sale 객체를 정의한다. 11 Sale cashier1(0.06, 24.95); 12 13 // 면세 매상이  $24.95인 Sale 객체를 정의한다. 14 Sale cashier2(24.95); 15 16 cout << fixed << showpoint << setprecision(2); 17 cout << "With a 0.06 sales tax rate, the total\n"; 18 cout << "of the $24.95 sale is $"; 19 cout << cashier1.getTotal() << endl; 20 cout << "On a tax-exempt purchase, the total\n"; 21 cout << "of the $24.95 sale is, of course, $"; 22 cout << cashier2.getTotal() << endl; 23 return 0; 24 } 프로그램 출력 With a 0.06 sales tax rate, the total of the $24.95 sale is $26.45 On a tax-exempt purchase, the total of the $24.95 sale is, of course, $24.95 © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 93

7.16 소멸자 객체가 소멸될 때, 공개 멤버 함수인 소멸자가 자동으로 호출된다. 7.16 소멸자 객체가 소멸될 때, 공개 멤버 함수인 소멸자가 자동으로 호출된다. 소멸자 이름은 ~className, 예, ~Square 반환형이 없다. 인자가 없다. (매개변수 목록이 없음) 클래스 당 하나의 소멸자만 가진다. (과적 불가) See pr7-15.cpp © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 94

프로그램 7-15  1 // 이 프로그램은 소멸자 사용의 예를 보여준다.  2 #include <iostream>  3 using namespace std;  4  5 class Demo  6 {  7     public:  8              Demo();        // 생성자 원형  9             ~Demo();       // 소멸자 원형 10 }; 11 12 Demo::Demo()               // 생성자 함수 정의 13 {   cout << "An object has just been defined, so the constructor" 14          << " is running.\n"; 15 } 16 Demo::~Demo()              // 소멸자 함수 정의 17 {   cout << "Now the destructor is running.\n"; } 18 19 int main() 20 { 21     Demo demoObj;          // Demo 객체를 선언한다. 22 23     cout << "The object now exists, but is about to be destroyed.\n"; 24     return 0; 25 } 프로그램 출력 An object has just been defined, so the constructor is running. The object now exists, but is about to be destroyed. Now the destructor is running. © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 95

7.17 입력 검증 객체 객체는 사용자의 입력을 검증하기 위해 설계될 수 있다. 허용 가능한 메뉴 선택을 보장하기 위해 7.17 입력 검증 객체 객체는 사용자의 입력을 검증하기 위해 설계될 수 있다. 허용 가능한 메뉴 선택을 보장하기 위해 유효한 값의 범위에 속하도록 보장 etc. See pr7-16.cpp, CharRange.cpp, and CharRange.h © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 96

입력 검증 객체 CharRange 입력 검증 클래스 이제 CharRange 클래스를 검토해보자. CharRange 클래스의 객체는 사용자에게 하나의 문자를 입력받아 그 문자가 규정된 범위의 문자에 속하는지 검증한다. 사용자가 규정된 범위를 벗어나는 문자를 입력하게 되면 객체는 오류 메시지를 출력하고, 사용자가 다시 문자를 입력하도록 기다린다. 이 클래스에 대한 코드는 다음과 같다. © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 97

char lower; // 가장 낮은 유효 문자 char upper; // 가장 높은 유효 문자 public: CharRange.h 내용 #ifndef CHRANGE_H #define CHRANGE_H class CharRange {     private:         char input;              // 사용자 입력         char lower;             // 가장 낮은 유효 문자         char upper;             // 가장 높은 유효 문자     public:         CharRange(char, char);         char getChar(); }; #endif © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 98

Chapter 7 Starting Out with C++: Early Objects 5/e slide 99 CharRange.cpp 내용 #include <iostream> #include <cctype>               // toupper 사용을 위해 요구된다. #include "CharRange.h" using namespace std; //********************************************* // CharRange 생성자                         * CharRange::CharRange(char l, char u) {         lower = toupper(l);         upper = toupper(u); } // CharRange 멤버 함수 getChar              * // 하나의 문자를 입력받아 올바른 범위에 있는지 * // 검증한다. 다음으로 유효한 문자를           * // 반환한다.                                 * char CharRange::getChar()         cin.get(input);           // 하나의 문자를 입력받는다.         cin.ignore();             // 입력 버퍼의 '\n'을 무시한다.         input = toupper(input);   // 대문자로 변환한다.         // 문자가 올바른 범위에 있는지 보장한다.         while (input < lower || input > upper)         {       cout << "That is not a valid character.\n";                 cout << "Enter a value from " << lower;                 cout << " to " << upper << ".\n";                 cin.get(input);                 cin.ignore();                 input = toupper(input);         }         return input; © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 99

Chapter 7 Starting Out with C++: Early Objects 5/e slide 100 프로그램 7-16  1 // 이 프로그램은 CharRange 클래스를 사용하며, 이 클래스의 역할을 보여준다.  2 // 이 파일은 CharRange.h와 CharRange.cpp 파일과 함께 하나의 프로젝트에  3 // 결합되어야 한다.  4  5 #include <iostream>  6 #include "CharRange.h"  7 using namespace std;  8  9 int main() 10 { 11     char ch;                        // 사용자 입력을 보관한다. 12 13     CharRange input('J', 'N');          // 이름이 input인 CharRange 객체를 생성한다. 14                                     // 범위가 J - N에 있는 문자인지 점검한다. 15 16     cout << "Enter any of the characters J, K, L, M, or N.\n"; 17     cout << "Entering N will stop this program.\n"; 18     ch = input.getChar(); 19     while (ch != 'N') 20     {       cout << "You entered " << ch << endl; 21             ch = input.getChar(); 22     } 23     return 0; 24 } 프로그램 출력(입력 예는 굵은 글씨) Enter any of the characters J, K, L, M, or N. Entering N will stop this program. j[Enter] You entered J L[Enter] You entered L p[Enter] That is not a valid character. Enter a value from J to N. m[Enter] You entered M n[Enter] © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 100

7.18 Private 멤버 함수의 사용 private 멤버 함수는 같은 클래스 내의 다른 멤버 함수에 의해서만 호출되는 멤버함수 이다. 클래스의 외부에서 사용을 위한 것이 아니라 클래스 내부 처리를 위해서만 사용된다. See pr7-17.cpp © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 101

1 // 이 프로그램은 비공개 멤버 함수의 사용 예를 보여준다. 2 // 또한 객체를 함수의 인자로 전달하는 방법을 보여준다. 프로그램 7-17  1 // 이 프로그램은 비공개 멤버 함수의 사용 예를 보여준다.  2 // 또한 객체를 함수의 인자로 전달하는 방법을 보여준다.  3 #include <iostream>  4 using namespace std;  5  6 // Class declaration  7 class BigNum  8 {  9     private: 10             int biggest; 11             void determineBiggest(int num) 12             { if (num > biggest) 13             biggest = num; 14             } 15     public: 16             BigNum()       // 디폴트 생성자 17             { biggest = 0; } 18             bool examineNum(int); 19             int getBiggest() 20             { return biggest; } 21 }; 22 © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 102

23 //********************************************************* 24 //                   BigNum::examineNum             * 25 // 이 공개 멤버 함수는 하나의 정수 값을 받는다.           * 26 // 그 값이 0보다 크면, 새로 입력받은 수가 지금까지 받은   * 27 //  값보다 큰지를 점검하기 위해 비공개 함수              * 28 // determineBiggest이 호출된다. 다음으로 클라이언트      * 29 // 프로그램에게 참이 반환된다. 음수를 받게 되면            * 30 // 처리되지 않고 거짓이 반환된다.                        * 31 //********************************************************* 32 bool BigNum::examineNum(int n) 33 { 34     bool goodValue = true; 35 36     if (n > 0) 37             determineBiggest(n); 38     else 39             goodValue = false; 40     return goodValue; 41 } 42 © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 103

43 //******************* 클라이언트 프로그램 ********************** 44 45 void getNumbers(BigNum &); 46 47 int main() 48 { 49     BigNum stockShares;    // BigNum 객체를 생성한다. 50 51     cout << "This program determines which stock purchase involved\n" 52     << "the largest number of shares of stock.\n\n"; 53     getNumbers(stockShares); 54     cout << "\nThe largest number of shares bought was " 55     << stockShares.getBiggest()<< ".\n"; 56     return 0; 57 } 58 © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 104

59 //********************************************************* 60 //                   getNumbers                      * 61 // 이 함수는 BigNum 객체를 받는다. 이 함수는            * 62 // 숫자를 입력받고, 이를 검사하기 위해 객체의              * 63 // examineNum 함수를 호출한다.                        * 64 //********************************************************* 65 void getNumbers(BigNum &stock) 66 {   int numTrans, 67     numShares; 68 69     cout << "How many stock purchases have you made this month? "; 70     cin >> numTrans; 71 72     for (int trans = 1; trans <= numTrans; trans++) 73     {       cout << "Purchase " << trans << " shares purchased: "; 74             cin >> numShares; 75             while (!stock.examineNum(numShares)) 76             {       cout << "The number entered should be greater than 0.\n" 77                     << "Re-enter the number of stock shares purchased: "; 78                     cin >> numShares; 79             } 80     } 81 } © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 105

This program determines which stock purchase involved 프로그램 출력(입력 예는 굵은 글씨) This program determines which stock purchase involved the largest number of shares of stock. How many stock purchases have you made this month? 3[Enter] Purchase 1 shares purchased: 400[Enter] Purchase 2 shares purchased: 900[Enter] Purchase 3 shares purchased: 0[Enter] The number entered should be greater than 0. Re-enter the number of stock shares purchased: 650[Enter] The largest number of shares bought was 900. © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 106

7.19 홈 소프트웨어 회사 OOP 사례연구 은행 계좌의 기본적인 동작을 모델화하는 클래스 설계 계좌(account)의 잔액(balance)를 저장한다. 계좌 상에서 수행된 거래(transaction) 수를 저장한다. 계좌에 입금(deposit)이 되게 한다. 계좌로부터 출금(withdraw)이 되게 한다. 이제까지의 이자를 계산한다. 계좌의 현재 잔액를 보고한다. 이제까지의 거래 수를 보고한다. © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 107

홈 소프트웨어 회사 비공개 멤버 변수 변수 설명 balance 계좌의 현 잔액을 저장하는 double intRate interest 이제까지 이자를 저장하는 double transaction 이제까지 총 거래 수를 저장하는 int © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 108

공개 멤버 함수 함수 설명 constructor balance와 intRate 멤버의 초기값을 인자로 가진다. balance의 디폴트 값은 0이고 intRate의 디폴트 값은 0.045이다. makeDeposit 입금액으로 double 인자를 받아 잔액에 더한다. withdraw 출금액으로 double 인자를 취한다. 출금액이 잔액보다 크지 않으면 이 값을 잔액에서 뺀다. 잔액보다 큰 경우에는 오류를 보고한다. calcInterest 인자가 없다. 이 함수는 현 시점의 이자 금액을 계산하고 interest 멤버에 이 값을 저장한 다음, balance 멤버에 더한다. getBalance balance 멤버에 저장된 잔고를 반환한다. getInterest interest 멤버에 저장된 이제까지의 이자를 반환한다. getTransactions transactions 멤버에 저장된 이제까지의 거래 수를 반환한다. © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 109

클래스 선언 account.h 내용 // 파일 account.h는 Account 클래스에 대한 클래스 선언을 포함한다.         class Account         {         private:                 double balance;                 double intRate;                 double interest;                 int transactions;         public:                 Account(double iRate = 0.045, double bal = 0)                  { balance = bal; intRate = iRate;                    interest = 0; transactions = 0;                  }                 void makeDeposit(double amount)                  { balance += amount; transactions++; }                 bool withdraw(double amount);   // account.cpp에서 정의된다.                 void calcInterest()                  { interest = balance * intRate; balance += interest; }                 double getBalance()                  { return balance; }                 double getInterest()                  { return interest; }                 int getTransactions()                  { return transactions; }         }; © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 110

Withdraw 멤버 함수 account.cpp 내용 // account.cpp-Account 클래스에 대한 구현 파일         #include "account.h"         bool Account::withdraw(double amount)         {                 if (balance < amount)                         return false; // 계좌에 충분한 잔고가 없음                 else                 {                         balance -= amount;                         transactions++;                         return true;                 }         } © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 111

객체의 인터페이스 balance, intRate, interest, transactions 멤버 변수는 비공개 프로그래머에게 변수들에 대한 직접적인 접근 권한을 주게 되면, 프로그래머가 인지하지 않은 상태에서 다음과 같은 오류를 범할 수 있기 때문에 비공개로 한다.  transactions 멤버가 증가되지 않고서도 입금이나 출금이 행해질 수 있다.  계좌에 있는 잔고보다 큰 금액의 출금이 발생하여 balance 멤버가 음수 값이 되게 할 수 있다.  intRate 멤버에 저장된 이율이 아닌 값으로 이자를 계산하고 balance 멤버가 조정될 수 있다.  틀린 이율이 사용될 수 있다. © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 112

클래스의 구현 Account 클래스의 구현 예금계좌의 잔액,거래 수,이자 출력 메뉴 입금, 출금, 이자 계산 CharRange 입력 검증 객체 사용 © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 113

Chapter 7 Starting Out with C++: Early Objects 5/e slide 114 프로그램 7-18  1 // 이 프로그램은 은행 업무를 수행하기 위해 Accout 클래스를 사용한다.  2 //  이 파일은 account.h와 account.cpp, CharRange.h, CharRange.cpp 파일과  3 // 함께 하나의 프로젝트에 결합되어야 한다.  4 #include <iostream>  5 #include <iomanip>  6 #include <cctype>  7 #include "account.h"  8 #include "CharRange.h"  9 using namespace std; 10 11 // 함수 원형 12 void displayMenu(); 13 void makeDeposit(Account &); 14 void withdraw(Account &); 15 16 int main() 17 { 18     Account savings;                // 예금 계좌를 모델화 하는 Account 객체 19     CharRange input('A', 'G');        // 입력 검증을 하는 CharRange 객체 20     char choice; 21 22     cout << fixed << showpoint << setprecision(2); 23 24     do 25     { 26             displayMenu(); 27             choice = input.getChar(); // 대문자 A - G 만 반환한다. 28             switch(choice) 29             { 30                     case 'A': cout << "The current balance is $"; 31                              cout << savings.getBalance() << endl; 32                              break; 33                     case 'B': cout << "There have been "; 34                              cout << savings.getTransactions() 35                                     << " transactions.\n"; 36                              break; 37                     case 'C': cout << "Interest earned for this period: $"; 38                              cout << savings.getInterest() << endl; 39                              break; 40                     case 'D': makeDeposit(savings); © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 114

Chapter 7 Starting Out with C++: Early Objects 5/e slide 115 41                              break; 42                     case 'E': withdraw(savings); 43                              break; 44                     case 'F': savings.calcInterest(); 45                              cout << "Interest added.\n"; 46             } 47     } while(choice!= 'G'); 48     return 0; 49 } 50 51 //*************************************************************** 52 //                   displayMenu                            * 53 // 이 함수는 화면에 사용자 메뉴를 출력한다.                    * 54 //*************************************************************** 55 void displayMenu() 56 { 57     cout << "\n Menu\n\n”; 58     cout << "a) Display the account balance\n"; 59     cout << "b) Display the number of transactions\n"; 60     cout << "c) Display interest earned for this period\n"; 61     cout << "d) Make a deposit\n"; 62     cout << "e) Make a withdrawal\n"; 63     cout << "f) Add interest for this period\n"; 64     cout << "g) Exit the program\n\n"; 65     cout << "Enter your choice: "; 66 } 67 68 //*************************************************************** 69 //                   makeDeposit                            * 70 // 이 함수는 Account 객체에 대한 참조를 받는다.                 * 71 // 사용자에게 입금할 금액($)을 요구한 후,                       * 72 // Account 객체의 makeDeposit 멤버를                          * 73 // 호출한다.                                                  * 74 //*************************************************************** 75 void makeDeposit(Account &account) 76 { 77     double dollars; 78 79     cout << "Enter the amount of the deposit: "; 80     cin >> dollars; 81     cin.ignore(); 82     account.makeDeposit(dollars); 83 } © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 115

Chapter 7 Starting Out with C++: Early Objects 5/e slide 116 84 85 //*************************************************************** 86 //                           withdraw                       * 87 // 이 함수는 Account 객체에 대한 참조를 받는다.                 * 88 // 사용자에게 출금할 금액($)을 요구한 후,                       * 89 // Account 객체의 withdraw 멤버를 호출한다.                   * 90 //*************************************************************** 91 void withdraw(Account &account) 92 { 93     double dollars; 94 95     cout << "Enter the amount of the withdrawal: "; 96     cin >> dollars; 97     cin.ignore(); 98     if (!account.withdraw(dollars)) 99             cout << "ERROR: Withdrawal amount too large.\n\n"; 100 } 프로그램 출력(입력 예는 굵은 글씨)         Menu a) Display the account balance b) Display the number of transactions c) Display interest earned for this period d) Make a deposit e) Make a withdrawal f) Add interest for this period g) Exit the program Enter your choice: d[Enter] Enter the amount of the deposit: 500[Enter] © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 116

Chapter 7 Starting Out with C++: Early Objects 5/e slide 117         Menu a) Display the account balance b) Display the number of transactions c) Display interest earned for this period d) Make a deposit e) Make a withdrawal f) Add interest for this period g) Exit the program Enter your choice: a[Enter] The current balance is $500.00 Enter your choice: e[Enter] Enter the amount of the withdrawal: 700[Enter] ERROR: Withdrawal amount too large. Enter the amount of the withdrawal: 200[Enter]   © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 117

Chapter 7 Starting Out with C++: Early Objects 5/e slide 118        Menu a) Display the account balance b) Display the number of transactions c) Display interest earned for this period d) Make a deposit e) Make a withdrawal f) Add interest for this period g) Exit the program Enter your choice: f[Enter] Interest added.         Menu Enter your choice: a[Enter] The current balance is: $313.50 Enter your choice: g[Enter] © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 118

7.20 소프트웨어 공학: 객체 지향 분석 계획단계(planning phase) : 객체 지향 분석 단계(Object-oriented analysis phase) 1. 프로그램 내에서 사용될 객체와 클래스를 정한다.  2. 각 클래스에 대한 속성(attribute)을 정의한다.  3. 각 클래스에 대한 동작(behavior)을 정의한다.  4. 클래스 사이의 관계(relationship)를 정의한다. © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 119

1. 객체와 클래스를 정한다. 클래스에 대한 후보가 될 수 있는 다양한 항목.  - 윈도즈, 메뉴, 대화 박스 같은 사용자 인터페이스 컴포넌트  - 키보드, 마우스, 화면, 프린트 같은 입출력 장치  - 자동차, 기계 또는 공산품 같은 실제 물체  - 고객의 과거 거래 내역, 급여 기록 같은 보관항목 - 사람(종업원, 고객, 선생, 학생 등)의 역할 © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 120

2. 각 클래스에 대한 속성을 정의한다. 클래스 이름: MenuItem // 식당 속성: itemName price    category      // 1 = appetizer, 2 = salad, 3 = entree                  // 4 = side dish, 5 = dessert, 6 = beverage 다음은 CustomerOrder 클래스에 대한 가능한 명세이다. 클래스 이름: CustomerOrder 속성: orderNumber    tableNumber    serverNumber    date   items          // MenuItem 객체의 리스트 : 합성    totalPrice    tip © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 121

3. 각 클래스에 대한 동작을 정의한다. 다음은 MenuItem 클래스가 수행하여야 할 행위의 예를 보여준다. - 가격의 변경  - 가격의 변경  - 가격의 출력 다음은 CustomerOrder 클래스가 수행하여야 할 행위의 예를 보여준다.  - 새 주문에 대한 정보의 입력  - 현 주문에 항목을 추가  - 이전 저장된 주문에 대한 정보를 반환  - 주문 상의 모든 항목에 대한 총 금액을 계산  - 주방에 보낼 주문 리스트 출력  - 고객에게 줄 계산서 출력 C++에서 클래스의 행위는 클래스의 멤버 함수이다. © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 122

4. 클래스 사이의 관계를 정의한다. - 접근 관계(access)  - 소유 관계(ownership) 또는 합성 관계(composition)  - 상속 관계(inheritance) 약식으로는 다음과 같이 기술한다.  - Uses-a  - Has-a  - Is-a 11장에서 설명! 기본클래스 파생클래스 © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 123

7.22 복습 및 연습 문제 다음 빈칸을 채우고 간단히 답하라. 1. 구조체 변수는 생성되기 전에  _________되어야 한다. 2. _______은(는) 구조체 형의 이름이다. 3. 구조체 선언 내에서 선언된 변수는 ________(이)라 한다. 4. 구조체 선언의 닫는 중괄호 다음에 ________가(이) 요구된다. 5. 구조체 변수의 정의에서 _______가(이) 변수명 앞에 온다. 6. ______ 연산자는 구조체 멤버에 접근하게 한다. 7. Inventory 구조체가 다음과 같이 선언되었다.         struct Inventory         {       int itemCode;                 int qtyOnHand;         }; 이름이 trivet이라는 Inventory 변수를 생성하고, 초기화 목록을 사용하여 초기화하여 code가 555가 되고 quantity가 110이 되게 초기화하는 정의 문장을 작성하라. 8. Car 구조체가 다음과 같이 선언되었다.         struct Car         {  string  make,                         model;                 int     year;                 double  cost;                 Car(string mk, string md, int y, double c)                 {       make = mk; model = md; year = y; cost = c; } }; 다음 정보를 이용하여 초기화하는 Car 구조체 변수의 정의문을 작성하라.         Make: Ford         Model: Mustang         Year: 2004         Cost: $25,000 © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 124

16. 오늘날 실제 사용하고 있는 두 가지 공통적인 프로그래밍 방법은 ______와(과) ________이다. 17. _________ 프로그래밍은 함수나 프로시저를 중심으로 한다. 18. _________ 프로그래밍은 객체를 중심으로 한다. 19. ________은(는) 자신의 자료를 가지고 조작하는 객체의 능력이다. 20. C++에서 ________은(는) 주로 객체를 생성하기 위한 것이다. 21. 클래스는 ________와(과) 유사하다. 22. C++에서 구조체 멤버의 디폴트 접근 명세는 ________이다. 23. 클래스 멤버의 디폴트 접근 명세는 ________이다. 24. 객체는 클래스의 ________이다. 25. 클래스 객체를 정의하는 것을 클래스의 ________이라 한다. 26. 이름이 Canine인 클래스 선언문을 작성할 때, 선언문을 저장하는 파일의 이름은? 27. 클래스 외부에서 Canine 클래스의 멤버 함수를 정의하려면 어떤 파일 이름으로 저장하여야 하나? 28. 멤버 함수의 몸체가 클래스 선언 내에서 작성될 때 함수는 _______ 함수이다. 29. 생성자는 ________와(과) 같은 이름을 가진 멤버 함수이다. 30. 생성자는 객체가 ________될 때 자동으로 호출된다. 31. 생성자는 _______형을 가질 수 없다. 32. ________ 생성자는 인자를 요구하지 않는 생성자이다. 33. 소멸자는 객체가 ________될 때 자동으로 호출되는 멤버 함수이다. 34. 소멸자는 클래스와 같은 이름을 가지지만 ________ 문자가 이름 앞에 온다. 35. 모든 매개변수가 디폴트 값을 가지는 생성자는 _______ 생성자이다. 36. 생성자가 서로 다른 ________를 가지면 클래스는 여러 개의 생성자를 가질 수 있다. 37. 클래스는 단지 하나의 디폴트 _______와 하나의 ______를 가질 수 있다. 38. 멤버 함수에서 ________의 사용을 피하는 것이 일반적으로 좋은 설계 방법이다. 39. 멤버 함수가 인터페이스의 일부를 만들 때 클라이언트 프로그램이 클래스를 사용할 수 있도록 그 함수는 ________이여야 한다. 40. 멤버 함수가 클래스 내부의 일만을 수행하고, 클라이언트 프로그램에 의해서 호출되지 않아야 할 때 그 함수는 ________이여야 한다. © 2006 Pearson Education. All Rights Reserved Chapter 7 Starting Out with C++: Early Objects 5/e slide 125

Starting Out with C++: Early Objects 5th Edition Chapter 7 클래스와 객체에 대한 소개 Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved