140 likes | 253 Vues
Chapter 6: Classes and Data Abstraction. Outline 6.1 Introduction 6.2 Structure Definitions 6.3 Accessing Members of Structures 6.4 Implementing a User-Defined Type Time with a Struct 6.5 Implementing a Time Abstract Data Type with a Class 6.6 Class Scope and Accessing Class Members
E N D
Chapter 6: Classes andData Abstraction Outline 6.1 Introduction 6.2 Structure Definitions 6.3 Accessing Members of Structures 6.4 Implementing a User-Defined Type Time with a Struct 6.5 Implementing a Time Abstract Data Type with a Class 6.6Class Scope and Accessing Class Members 6.7 Separating Interface from Implementation 6.8 Controlling Access to Members 6.9 Access Functions and Utility Functions 6.10 Initializing Class Objects: Constructors 6.11 Using Default Arguments with Constructors 6.12 Using Destructors 6.13 When Constructors and Destructors Are Called 6.14 Using Data Members and Member Functions 6.15 A Subtle Trap: Returning a Reference to a Private Data Member 6.16 Assignment by Default Memberwise Copy 6.17 Software Reusability
6.6 Class Scope and Accessing Class Members • 클래스 범위(Class scope) • 데이터멤버, 멤버함수를 직접 이름으로 접근 • 클래스 외부 범위 • 데이터와 멤버함수는 클래스 핸들을 통해 접근 • 예: t.printStadard(), t->printStandard • 함수범위(Function scope) • 변수는 정의된 함수 내에서만 알려짐 • 함수 수행이 종료되면 변수도 소멸됨
6.6 Class Scope and Accessing Class Members • 클래스 멤버의 접근 • Structs와 동일함 • 객체의 경우 도트(.), 포인터의 경우 화살표(->)를 사용함 • 예: • t.hour는 t의 hour요소임 • TimePtr->hour역시 hour요소임
1. Class definition2. Create an object of the class2.1 Assign a value to the object. Print the value using the dot operator2.2 Set a new value and print it using a reference 1 // Fig. 6.4: fig06_04.cpp 2 // Demonstrating the class member access operators . and -> It is rare to have public member variables. Usually only member functions are public; this keeps as much information hidden as possible. 3 // 4 // CAUTION: IN FUTURE EXAMPLES WE AVOID PUBLIC DATA! 5 #include <iostream> 6 7 using std::cout; 8 using std::endl; 9 10 // Simple class Count 11 class Count { 12 public: 13 int x; 14 void print() { cout << x << endl; } 15 }; 16 17 int main() 18 { 19 Count counter, // create counter object 20 *counterPtr = &counter, // pointer to counter 21 &counterRef = counter; // reference to counter 22 23 cout << "Assign 7 to x and print using the object's name: "; 24 counter.x = 7; // assign 7 to data member x 25 counter.print(); // call member function print 26 27 cout << "Assign 8 to x and print using a reference: "; 28 counterRef.x = 8; // assign 8 to data member x 29 counterRef.print(); // call member function print 30 1. Class definition2. Create an object of the class2.1 Assign a value to the object. Print the value using the dot operator2.2 Set a new value and print it using a reference
31 cout << "Assign 10 to x and print using a pointer: "; 32 counterPtr->x = 10; // assign 10 to data member x 33 counterPtr->print(); // call member function print 34 return 0; 35 } 2.3 Set a new value and print it using a pointerProgram Output Assign 7 to x and print using the object's name: 7 Assign 8 to x and print using a reference: 8 Assign 10 to x and print using a pointer: 10
6.7 Separating Interface from Implementation • 인터페이스를 구현으로부터 분리 • 프로그램 수정을 용이하도록 함 • 해더파일(Header files) • 클래스 정의와 함수 원형을 저장 • 소스코드 파일 (Source-code files) • 멤버 함수의 정의를 포함
Execute Rebuild All Execute Compile and Run
# Compiler CC=g++ # Parameters given to the compiler CFLAGS=-s -IC:\DEV-C_~1\Include\ -IC:\DEV-C_~1\Include\G__~1 -IC:\DEV-C_~1\Include\ -LC:\DEV-C_~1\Lib\ -BC:\DEV-C_~1\Bin\ # Output filename (*.exe) OUTPUT="week2-HGD.exe" # Source files SRCS="C:\Fig6_05\WorkTime.cpp" "C:\\Fig6_05\test.cpp" # Output object files (*.o) OBJS="C:\Fig6_05\WorkTime.o" "C:\Fig6_05\test.o" "C:\Fig6_05\rsrc.o" # Standard targets all: compile_res $(CC) -c $(SRCS) $(CFLAGS) $(CC) -o $(OUTPUT) $(OBJS) $(CFLAGS) compile_res: windres --include-dir C:\DEV-C_~1\Include\ --include-dir C:\DEV-C_~1\Include\G__~1 --include-dir C:\DEV-C_~1\Include\ --use-temp-file -I rc -O coff -i "C:\강의\2003-2\프로그~1\ch06\Fig6_05\rsrc.rc" -o "C:\강의\2003-2\프로그~1\ch06\Fig6_05\rsrc.o" Makefile의 내용
1 //Fig. 6.5: time1.h 2 // Declaration of the Time class. 3 // Member functions are defined in time1.cpp Dot ( . ) replaced with underscore ( _ ) in file name. 4 If time1.h (TIME1_H) is not defined (#ifndef) then it is loaded (#defineTIME1_H). If TIME1_His already defined, then everything up to #endifis ignored. This prevents loading a header file multiple times. 5 // prevent multiple inclusions of header file 6 #ifndef TIME1_H 7 #define TIME1_H 8 9 // Time abstract data type definition 10 class Time { 11 public: 12 Time(); // constructor 13 void setTime( int, int, int ); // set hour, minute, second 14 void printMilitary(); // print military time format 15 void printStandard(); // print standard time format 16 private: 17 int hour; // 0 - 23 18 int minute; // 0 - 59 19 int second; // 0 - 59 20 }; 21 22 #endif 1. Using the same Time class as before, create a header file
23 // Fig. 6.5: time1.cpp 24 // Member function definitions for Time class. Source file uses #include to load the header file 25 #include <iostream> 26 27 using std::cout; 28 Source file contains function definitions 29 #include "time1.h" 30 31 // Time constructor initializes each data member to zero. 32 // Ensures all Time objects start in a consistent state. 33 Time::Time() { hour = minute = second = 0; } 34 35 // Set a new Time value using military time. Perform validity 36 // checks on the data values. Set invalid values to zero. 37 void Time::setTime( int h, int m, int s ) 38 { 39 hour = ( h >= 0 && h < 24 ) ? h : 0; 40 minute = ( m >= 0 && m < 60 ) ? m : 0; 41 second = ( s >= 0 && s < 60 ) ? s : 0; 42 } 43 44 // Print Time in military format 45 void Time::printMilitary() 46 { 47 cout << ( hour < 10 ? "0" : "" ) << hour << ":" 48 << ( minute < 10 ? "0" : "" ) << minute; 49 } 50 51 // Print time in standard format 52 void Time::printStandard() 53 { 54 cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ) 55 << ":" << ( minute < 10 ? "0" : "" ) << minute 56 << ":" << ( second < 10 ? "0" : "" ) << second 57 << ( hour < 12 ? " AM" : " PM" ); 58 } 2. Create a source code file2.1 Load the header file to get the class definitions2.2. Define the member functions of the class