Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights...

62
2003 Prentice Hall, Inc. All rights reserved. 1 作業一說明 作業一說明 2003 Prentice Hall, Inc. All rights reserved. Outline 2 // 作業一 : calculator // 引用標頭檔 #include <iostream> //引用輸入輸出函式 #include <cmath> //引用數學函式 using namespace std; //使用std命名空間 // Prototype int factorical(int); //計算階乘函式 double GetOperand(char *); //讀取運算元函式 inline void ClearKeyBoardBuffer(void); //清除鍵盤緩衝區函式 //主程式 int main(int argc, char **argv) { char Op; //運算子 double Op1; //第一個運算元 double Op2; //第二個運算元 int ParaErr=1;//記錄輸入參數是否正確,0表正確,1表錯誤 if ((argc==3)||(argc==4)) { //輸入參數三個或四個 if (argv[1][1]==0) //運算子只有一個字元 Op=argv[1][0]; //將第一個參數給Op //取得運算元 1.適當加註解 3.內縮 2.取得命令列參數

Transcript of Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights...

Page 1: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

1

2003 Prentice Hall, Inc. All rights reserved.

1

作業一說明作業一說明

2003 Prentice Hall, Inc.All rights reserved.

Outline2

// 作業一 : calculator// 引用標頭檔#include <iostream> //引用輸入輸出函式#include <cmath> //引用數學函式using namespace std; //使用std命名空間

// Prototypeint factorical(int); //計算階乘函式double GetOperand(char *); //讀取運算元函式inline void ClearKeyBoardBuffer(void); //清除鍵盤緩衝區函式

//主程式int main(int argc, char **argv){ char Op; //運算子 double Op1; //第一個運算元 double Op2; //第二個運算元 int ParaErr=1;//記錄輸入參數是否正確,0表正確,1表錯誤

if ((argc==3)||(argc==4)) { //輸入參數三個或四個 if (argv[1][1]==0) //運算子只有一個字元

Op=argv[1][0]; //將第一個參數給Op //取得運算元

1.適當加註解

3.內縮

2.取得命令列參數

Page 2: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

2

2003 Prentice Hall, Inc.All rights reserved.

Outline3

//取得運算元 switch (Op) { case '+': case '-': case '*': case '/': case 'p': case 'P': if (argc==4) {

Op1=atof(argv[2]); //讀取第一個運算元 Op2=atof(argv[3]); //讀取第二個運算元

if ((Op1!=0.0)&&(Op2!=0.0)) ParaErr=0; //參數正確 } break;

case '!': case 'r': case 'R':

if (argc==3) { Op1=atof(argv[2]); //讀取第一個運算元

if (Op1!=0.0) ParaErr=0; //參數正確 }

break; }

6.記得加break

5. 不同命令有不同參數個數

最好加break

4.命令有+,-,*,/,!,p,r

2003 Prentice Hall, Inc.All rights reserved.

Outline4

//如果輸入參數錯誤,要求使用者輸入參數if (ParaErr) { cout << "輸入參數錯誤\n";

//取得運算子 do {

ClearKeyBoardBuffer(); //清除輸入緩衝區 cout << "請輸入運算子(+,-,*,/,!,r,p):"; cin >> Op; } while (!((Op=='+')||(Op=='-')||(Op=='*')||(Op=='/')||(Op=='!')

||(Op=='r')||(Op=='R')||(Op=='p')||(Op=='P')));

//取得第一個運算元 Op1=GetOperand("請輸入第一個運算元:");

//取得第二個運算元 if ((Op!='!')&&(Op!='r')&&(Op!='R')) { Op2=GetOperand("請輸入第二個運算元:"); }}

9.加括號

8.要有提示字串

7.要有使用者輸入部份

Page 3: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

3

2003 Prentice Hall, Inc.All rights reserved.

Outline5

//計算並印出結果switch (Op) { case '+': cout << Op1 << '+' << Op2 << '=' << Op1+Op2 << endl; break; case '-': cout << Op1 << '-' << Op2 << '=' << Op1-Op2 << endl; break; case '*': cout << Op1 << '*' << Op2 << '=' << Op1*Op2 << endl; break; case '/': cout << Op1 << '/' << Op2 << '=' << Op1/Op2 << endl; break; case 'p': case 'P': cout << "Pow("<< Op1 << ',' << Op2 << ")=" << pow(Op1,Op2) << endl; break; case '!': cout << Op1 << "!=" << factorical(Op1) << endl;

break; case 'r': case 'R': cout << "sqrt(" << Op1 << ")=" << sqrt(Op1) << endl; break;}return(0);

}

10.印出正確結果

2003 Prentice Hall, Inc.All rights reserved.

Outline6

//計算階乘函式int factorical(int num){ if ((num==1)||(num==0)) {

return(1);} else return(num*factorical(num-1));

}

//輸入一個運算元double GetOperand(char *Message){ double Data;

ClearKeyBoardBuffer(); //清除輸入緩衝區 cout << Message; //顯示提示字串 do { while(!(cin>>Data)) {

cin.clear(); //清除cin狀態 cin.seekg(0,ios::end); //清除輸入緩衝區 cout << Message; //顯示提示字串 } } while ((cin.peek()!='\n')&&(cin.peek()!=' '));

return(Data);}

//清除鍵盤緩衝區inline void ClearKeyBoardBuffer(void){cin.seekg(0,ios::end);}

Page 4: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

4

2003 Prentice Hall, Inc. All rights reserved.

7

UMLUML類別圖與類別定義類別圖與類別定義

2003 Prentice Hall, Inc. All rights reserved.

8

UML類別圖

Time

- hour : integer- minute : integer- second : integer

+ Time()+ setTime(hour:Integer, minute:Integer, second:Integer )+ printUniversal()+ printStandard()

類別名稱(Class Name)

資料成員(Data Member)

成員函式(Member Function)

減號表private

加號表public

Page 5: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

5

2003 Prentice Hall, Inc. All rights reserved.

9

1 class Time {23 public:4 Time(); // constructor5 void setTime( int, int, int ); // set hour, minute, second6 void printUniversal(); // print universal-time format7 void printStandard(); // print standard-time format89 private:10 int hour; // 0 - 23 (24-hour clock format)11 int minute; // 0 - 5912 int second; // 0 - 591314 }; // end class Time

類別定義

2003 Prentice Hall, Inc.All rights reserved.

Outline10

Count

+ x : Integer

+ print()

UML類別圖

Page 6: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

6

2003 Prentice Hall, Inc. All rights reserved.

11

1 // class Count definition2 class Count {34 public:5 int x;6 void print();78 }; // end class Count

類別定義

2003 Prentice Hall, Inc.All rights reserved.

Outline12

SalesPerson- totalAnnualSales : Double- sales[12] : Double+ SlaesPerson()+ getSalesFromUser()+ setSales( month: Integer, quantity: Double )+ printAnnualSales()

UML類別圖

Page 7: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

7

2003 Prentice Hall, Inc.All rights reserved.

Outline13

1 class SalesPerson {23 public:4 SalesPerson(); // constructor5 void getSalesFromUser(); // input sales from keyboard6 void setSales( int, double ); // set sales for a month7 void printAnnualSales(); // summarize and print sales89 private:10 double totalAnnualSales(); // utility function11 double sales[ 12 ]; // 12 monthly sales figures1213 }; // end class SalesPerson

類別定義

2003 Prentice Hall, Inc.All rights reserved.

Outline14

Date- month : Integer- day : Integer- year : Integer+ Date(month : Integer = 1, day :Integer = 1, year : Integer = 1990)+ print()

UML類別圖

初始值

Page 8: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

8

2003 Prentice Hall, Inc.All rights reserved.

Outline15

類別定義

1 // class Date definition2 class Date {34 public:5 Date( int = 1, int = 1, int = 1990 ); // default constructor6 void print();78 private:9 int month;10 int day;11 int year;12 }; // end class Date

2003 Prentice Hall, Inc.All rights reserved.

Outline16

fig06_24.cpp(2 of 3)

23 // Date constructor with no range checking24 Date::Date( int m, int d, int y )25 {26 month = m;27 day = d;28 year = y;2930 } // end Date constructor3132 // print Date in the format mm-dd-yyyy33 void Date::print()34 {35 cout << month << '-' << day << '-' << year;3637 } // end function print38

類別實作

Page 9: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

9

2003 Prentice Hall, Inc. All rights reserved.

17

作業三 - 撲克牌遊戲

• 1. Card物件– Data - Color (const), Point (const)– Function - print(), getColor(), getPoint()

• 2. Dealer物件– Data - card[52], numCard– Function - pushCard(card), Shuffle(), Deal(Num, Player),

Print()

2003 Prentice Hall, Inc. All rights reserved.

18

• 3. Player物件– Data - card[52], numCard, money– Function - pushCard(card), popCard(), print(), sort(),

showHand()

Page 10: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

10

2003 Prentice Hall, Inc. All rights reserved.

19

• 4. 主程式– a.產生52張牌, 一個Dealer, 一個Player(1000元)– b.將52張牌給Dealer– c.顯示player目前手上金額並押注– d.Dealer洗牌並發5張牌給player– e.印出player手上的牌– f. 排序player手上的牌, 印出player手上的牌– g.顯示player的輸贏結果– h.顯示player目前手上金額– i.收回player手上的牌並傳給Dealer– j.如果player金額大於零,詢問是否繼續玩– k.繼續玩, 回到步驟c.

2003 Prentice Hall, Inc. All rights reserved.

20

• 5. 倍率表– 同花順 X1000– 鐵支 X500– 葫蘆 X300– 同花 X200– 順子 X100– 三條 X20– 兩對 X10– 一對 X5

Page 11: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

11

2003 Prentice Hall, Inc. All rights reserved.

21

5/10 交類別定義

5/24 類別實作

6/14 完整程式

2003 Prentice Hall, Inc. All rights reserved.

22

Problems

• 什麼是建構子(Constructors)• 什麼是解構子(Destructors)• Public與Private有何不同• 成員函式定義在class內相當於什麼效果• 成員函式定義在class外要如何定義

– 例如: Date 的 print()函式

• 如何取用物件的成員

Page 12: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

12

2003 Prentice Hall, Inc. All rights reserved.

23

Chapter 6: Classes andData Abstraction

•Structure Definitions and Time struct

•Class Definitions and Time class

•Data member and member function

•Accessing Class Members

•Interface and Implementation

•Utility Functions

•Constructors and Destructors

•Set and Get Functions

2003 Prentice Hall, Inc. All rights reserved.

24

Chapter 7: Classes Part II

Outline7.1 Introduction7.2 const (Constant) Objects and const Member Functions7.3 Composition: Objects as Members of Classes7.4 friend Functions and friend Classes7.5 Using the this Pointer7.6 Dynamic Memory Management with Operators new and delete7.7 static Class Members7.8 Data Abstraction and Information Hiding7.9 Container Classes and Iterators7.10 Proxy Classes

Page 13: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

13

2003 Prentice Hall, Inc. All rights reserved.

25

7.1 Introduction

• 本章將繼續討論類別與資料抽象化• 在第6-8章中

– 介紹以物件為基礎的程式設計• Object-based programming (OBP)

• 在第9-10章中– 介紹繼承(Inheritance)與多型(polymorphism)– Object-Oriented programming (OOP)

2003 Prentice Hall, Inc. All rights reserved.

26

7.2 const (Constant) Objects and constMember Functions

• 目的在提供最小的使用權限(least privilege)– 只允許修改必要物件– 適當的使用const

Page 14: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

14

2003 Prentice Hall, Inc. All rights reserved.

27

7.2 const (Constant) Objects and constMember Functions

• Keyword const– 指明物件不能被修改– 企圖修改const物件會產生Compiler error– Example

const Time noon( 12, 0, 0 );– const物件的值只能透過初始化過程給定

2003 Prentice Hall, Inc. All rights reserved.

28

• const 成員函式– const物件的成員函式必須是const才能被呼叫

• 函式內不能修改物件內容

– const物件中非const的成員函式無法被呼叫

7.2 const (Constant) Objects and constMember Functions

Page 15: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

15

2003 Prentice Hall, Inc. All rights reserved.

29

7.2 const (Constant) Objects and constMember Functions

• 將函式指定為 const的方式– Prototype

int getHour() const;– Definition

int Time::getHour() const{ return hour;} // end function getHour

2003 Prentice Hall, Inc. All rights reserved.

30

7.2 const (Constant) Objects and constMember Functions

• Constructors與destructors不能是const– 要能夠修改物件內容– Constructor

• 初始化物件– Destructor

• 執行termination housekeeping動作

Page 16: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

16

2003 Prentice Hall, Inc. All rights reserved.

31

constconst物件及物件及constconst成員函式使用範例成員函式使用範例

2003 Prentice Hall, Inc.All rights reserved.

Outline32

time5.h (1 of 2)1 // Fig. 7.1: time5.h2 // Definition of class Time.3 // Member functions defined in time5.cpp.4 #ifndef TIME5_H5 #define TIME5_H67 class Time {89 public:10 Time( int = 0, int = 0, int = 0 ); // default constructor1112 // set functions13 void setTime( int, int, int ); // set time14 void setHour( int ); // set hour15 void setMinute( int ); // set minute16 void setSecond( int ); // set second1718 // get functions (normally declared const)19 int getHour() const; // return hour20 int getMinute() const; // return minute21 int getSecond() const; // return second2223 // print functions (normally declared const)24 void printUniversal() const; // print universal time25 void printStandard(); // print standard time

類別定義類別定義

Set函式不能設為const

設定成const才能被存取

Page 17: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

17

2003 Prentice Hall, Inc.All rights reserved.

Outline33

time5.h (2 of 2)

2627 private:28 int hour; // 0 - 23 (24-hour clock format)29 int minute; // 0 - 5930 int second; // 0 - 593132 }; // end class Time3334 #endif

2003 Prentice Hall, Inc.All rights reserved.

Outline34

time5.cpp (1 of 4)1 // Fig. 7.2: time5.cpp2 // Member-function definitions for class Time.3 #include <iostream>45 using std::cout;67 #include <iomanip>89 using std::setfill;10 using std::setw;1112 // include definition of class Time from time5.h13 #include "time5.h"1415 // constructor function to initialize private data;16 // calls member function setTime to set variables;17 // default values are 0 (see class definition)18 Time::Time( int hour, int minute, int second )19 {20 setTime( hour, minute, second );2122 } // end Time constructor23

類別實作類別實作

Page 18: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

18

2003 Prentice Hall, Inc.All rights reserved.

Outline35

time5.cpp (2 of 4)

24 // set hour, minute and second values25 void Time::setTime( int hour, int minute, int second )26 {27 setHour( hour );28 setMinute( minute );29 setSecond( second );3031 } // end function setTime3233 // set hour value34 void Time::setHour( int h )35 {36 hour = ( h >= 0 && h < 24 ) ? h : 0;3738 } // end function setHour3940 // set minute value41 void Time::setMinute( int m )42 {43 minute = ( m >= 0 && m < 60 ) ? m : 0;4445 } // end function setMinute46

2003 Prentice Hall, Inc.All rights reserved.

Outline36

time5.cpp (3 of 4)

47 // set second value48 void Time::setSecond( int s )49 {50 second = ( s >= 0 && s < 60 ) ? s : 0;5152 } // end function setSecond5354 // return hour value55 int Time::getHour() const56 {57 return hour;5859 } // end function getHour6061 // return minute value62 int Time::getMinute() const63 {64 return minute;6566 } // end function getMinute67

Page 19: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

19

2003 Prentice Hall, Inc.All rights reserved.

Outline37

time5.cpp (4 of 4)

68 // return second value69 int Time::getSecond() const70 {71 return second;7273 } // end function getSecond7475 // print Time in universal format76 void Time::printUniversal() const77 {78 cout << setfill( '0' ) << setw( 2 ) << hour << ":"79 << setw( 2 ) << minute << ":"80 << setw( 2 ) << second;8182 } // end function printUniversal8384 // print Time in standard format85 void Time::printStandard() // note lack of const declaration86 {87 cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 )88 << ":" << setfill( '0' ) << setw( 2 ) << minute89 << ":" << setw( 2 ) << second90 << ( hour < 12 ? " AM" : " PM" );9192 } // end function printStandard

2003 Prentice Hall, Inc.All rights reserved.

Outline38

fig07_03.cpp(1 of 2)

1 // Fig. 7.3: fig07_03.cpp2 // Attempting to access a const object with3 // non-const member functions.45 // include Time class definition from time5.h6 #include "time5.h"78 int main()9 {10 Time wakeUp( 6, 45, 0 ); // non-constant object11 const Time noon( 12, 0, 0 ); // constant object1214 wakeUp.setHour( 18 ); // non-const non-const1516 noon.setHour( 12 ); // const non-const1718 wakeUp.getHour(); // non-const const1920 noon.getMinute(); // const const21 noon.printUniversal(); // const const2223 noon.printStandard(); // const non-const2425 return 0;2627 } // end main

主程式主程式

哪裏錯了?

const不能改值

Page 20: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

20

2003 Prentice Hall, Inc.All rights reserved.

Outline39

fig07_03.cpp(2 of 2)

fig07_03.cppoutput (1 of 1)

d:\cpphtp4_examples\ch07\fig07_01\fig07_01.cpp(16) : error C2662: 'setHour' : cannot convert 'this' pointer from 'const class Time' to 'class Time &' Conversion loses qualifiersd:\cpphtp4_examples\ch07\fig07_01\fig07_01.cpp(23) : error C2662: 'printStandard' : cannot convert 'this' pointer from 'const class Time' to 'class Time &' Conversion loses qualifiers

16 noon.setHour( 12 ); // const non-const

23 noon.printStandard(); // const non-const

編譯結果

兩個錯誤

2003 Prentice Hall, Inc. All rights reserved.

40

7.2 const (Constant) Objects and constMember Functions

• 初始化const資料成員– 使用member initializer syntax

• 可供初始化所有資料成員• Must be used for

– const data members– Data members that are references

Page 21: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

21

2003 Prentice Hall, Inc. All rights reserved.

41

member initializer syntax使用範例

2003 Prentice Hall, Inc.All rights reserved.

Outline42

fig07_04.cpp(1 of 3)

1 // Fig. 7.4: fig07_04.cpp2 // Using a member initializer to initialize a3 // constant of a built-in data type.4 #include <iostream>56 using std::cout;7 using std::endl;89 class Increment {1011 public:12 Increment( int c = 0, int i = 1 ); // default constructor1314 void addIncrement()15 {16 count += increment;1718 } // end function addIncrement1920 void print() const; // prints count and increment2122 private:23 int count;24 const int increment; // const data member2526 }; // end class Increment

類別定義類別定義

Page 22: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

22

2003 Prentice Hall, Inc.All rights reserved.

Outline4328 // constructor

29 Increment::Increment( int c, int i )30 : count( c ), // initializer for non-const member31 increment( i ) // required initializer for const member32 {33 // empty body3435 } // end Increment constructor3637 // print count and increment values38 void Increment::print() const39 {40 cout << "count = " << count41 << ", increment = " << increment << endl;4243 } // end function print

fig07_04.cpp(2 of 3)

2003 Prentice Hall, Inc.All rights reserved.

Outline44

fig07_04.cpp(3 of 3)

fig07_04.cppoutput (1 of 1)

45 int main()46 {47 Increment value( 10, 5 );4849 cout << "Before incrementing: ";50 value.print();5152 for ( int j = 0; j < 3; j++ ) {53 value.addIncrement();54 cout << "After increment " << j + 1 << ": ";55 value.print();56 }5758 return 0;5960 } // end main

Before incrementing: count = 10, increment = 5After increment 1: count = 15, increment = 5After increment 2: count = 20, increment = 5After increment 3: count = 25, increment = 5

主程式主程式

Page 23: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

23

2003 Prentice Hall, Inc. All rights reserved.

45

不正確初始化const資料成員

2003 Prentice Hall, Inc.All rights reserved.

Outline46

fig07_05.cpp(1 of 3)

1 // Fig. 7.5: fig07_05.cpp2 // Attempting to initialize a constant of3 // a built-in data type with an assignment.4 #include <iostream>56 using std::cout;7 using std::endl;89 class Increment {1011 public:12 Increment( int c = 0, int i = 1 ); // default constructor1314 void addIncrement()15 {16 count += increment;1718 } // end function addIncrement1920 void print() const; // prints count and increment2122 private:23 int count;24 const int increment; // const data member2526 }; // end class Increment

類別定義類別定義

Page 24: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

24

2003 Prentice Hall, Inc.All rights reserved.

Outline47

fig07_05.cpp(2 of 3)

2728 // constructor29 Increment::Increment( int c, int i )30 { // Constant member 'increment' is not initialized31 count = c; // allowed because count is not constant32 increment = i; // ERROR: Cannot modify a const object3334 } // end Increment constructor3536 // print count and increment values37 void Increment::print() const38 {39 cout << "count = " << count40 << ", increment = " << increment << endl;4142 } // end function print43

類別實作類別實作

2003 Prentice Hall, Inc.All rights reserved.

Outline48

fig07_05.cpp(3 of 3)

fig07_05.cppoutput (1 of 1)

44 int main()45 {46 Increment value( 10, 5 );4748 cout << "Before incrementing: ";49 value.print();5051 for ( int j = 0; j < 3; j++ ) {52 value.addIncrement();53 cout << "After increment " << j + 1 << ": ";54 value.print();55 }5657 return 0;5859 } // end main

D:\cpphtp4_examples\ch07\Fig07_03\Fig07_03.cpp(30) : error C2758: 'increment' : must be initialized in constructor base/member initializer list D:\cpphtp4_examples\ch07\Fig07_03\Fig07_03.cpp(24) : see declaration of 'increment'D:\cpphtp4_examples\ch07\Fig07_03\Fig07_03.cpp(32) : error C2166: l-value specifies const object

企圖修改const資料成員 increment

主程式主程式

沒有使用member initializer syntax初始化 const資料成員 increment

Page 25: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

25

2003 Prentice Hall, Inc. All rights reserved.

49

7.3 Composition: Objects as Members ofClasses

• 合成(Composition)– 類別的資料成員包含其它類別的物件

• 物件的建構方式(Construction of objects)– 成員物件依宣稱次序建構

• 不是依列在建構子的成員初始化序列中的次序• 成員物件在其主物件(host objects)建構前先被建構

2003 Prentice Hall, Inc. All rights reserved.

50

合成物件建構範例

Page 26: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

26

2003 Prentice Hall, Inc.All rights reserved.

Outline51

date1.h (1 of 1)1 // Fig. 7.6: date1.h2 // Date class definition.3 // Member functions defined in date1.cpp4 #ifndef DATE1_H5 #define DATE1_H67 class Date {89 public:10 Date( int = 1, int = 1, int = 1900 ); // default constructor11 void print() const; // print date in month/day/year format12 ~Date(); // provided to confirm destruction order1314 private:15 int month; // 1-12 (January-December)16 int day; // 1-31 based on month17 int year; // any year1819 // utility function to test proper day for month and year20 int checkDay( int ) const;2122 }; // end class Date2324 #endif

DateDate類別定義類別定義

2003 Prentice Hall, Inc.All rights reserved.

Outline52

date1.cpp (1 of 3)1 // Fig. 7.7: date1.cpp2 // Member-function definitions for class Date.3 #include <iostream>45 using std::cout;6 using std::endl;78 // include Date class definition from date1.h9 #include "date1.h"1011 // constructor confirms proper value for month; calls12 // utility function checkDay to confirm proper value for day13 Date::Date( int mn, int dy, int yr )14 {15 if ( mn > 0 && mn <= 12 ) // validate the month16 month = mn;1718 else { // invalid month set to 119 month = 1;20 cout << "Month " << mn << " invalid. Set to month 1.\n";21 }2223 year = yr; // should validate yr24 day = checkDay( dy ); // validate the day25

DateDate類別實作類別實作

Page 27: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

27

2003 Prentice Hall, Inc.All rights reserved.

Outline53

date1.cpp (2 of 3)

26 // output Date object to show when its constructor is called27 cout << "Date object constructor for date ";28 print();29 cout << endl;3031 } // end Date constructor3233 // print Date object in form month/day/year34 void Date::print() const35 {36 cout << month << '/' << day << '/' << year;3738 } // end function print3940 // output Date object to show when its destructor is called41 Date::~Date()42 {43 cout << "Date object destructor for date ";44 print();45 cout << endl;4647 } // end destructor ~Date48

2003 Prentice Hall, Inc.All rights reserved.

Outline54

date1.cpp (3 of 3)

49 // utility function to confirm proper day value based on50 // month and year; handles leap years, too51 int Date::checkDay( int testDay ) const52 {53 static const int daysPerMonth[ 13 ] =54 { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };5556 // determine whether testDay is valid for specified month57 if ( testDay > 0 && testDay <= daysPerMonth[ month ] )58 return testDay;5960 // February 29 check for leap year61 if ( month == 2 && testDay == 29 &&62 ( year % 400 == 0 ||63 ( year % 4 == 0 && year % 100 != 0 ) ) )64 return testDay;6566 cout << "Day " << testDay << " invalid. Set to day 1.\n";6768 return 1; // leave object in consistent state if bad value6970 } // end function checkDay

Page 28: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

28

2003 Prentice Hall, Inc.All rights reserved.

Outline55

employee1.h (1 of 2)1 // Fig. 7.8: employee1.h2 // Employee class definition.3 // Member functions defined in employee1.cpp.4 #ifndef EMPLOYEE1_H5 #define EMPLOYEE1_H67 // include Date class definition from date1.h8 #include "date1.h"910 class Employee {1112 public:13 Employee(14 const char *, const char *, const Date &, const Date & );1516 void print() const;17 ~Employee(); // provided to confirm destruction order1819 private:20 char firstName[ 25 ];21 char lastName[ 25 ];22 const Date birthDate; // composition: member object23 const Date hireDate; // composition: member object2425 }; // end class Employee2627 #endif

員工員工(Employee)(Employee)類別定義類別定義

2003 Prentice Hall, Inc.All rights reserved.

Outline56

employee1.h (2 of 2)

employee1.cpp(1 of 3)

1 // Fig. 7.9: employee1.cpp2 // Member-function definitions for class Employee.3 #include <iostream>45 using std::cout;6 using std::endl;78 #include <cstring> // strcpy and strlen prototypes910 #include "employee1.h" // Employee class definition11 #include "date1.h" // Date class definition12

員工員工(Employee)(Employee)類別實作類別實作

Page 29: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

29

2003 Prentice Hall, Inc.All rights reserved.

Outline57

employee1.cpp(2 of 3)

13 // constructor uses member initializer list to pass initializer14 // values to constructors of member objects birthDate and15 // hireDate [Note: This invokes the so-called "default copy16 // constructor" which the C++ compiler provides implicitly.]17 Employee::Employee( const char *first, const char *last,18 const Date &dateOfBirth, const Date &dateOfHire )19 : birthDate( dateOfBirth ), // initialize birthDate20 hireDate( dateOfHire ) // initialize hireDate21 {22 // copy first into firstName and be sure that it fits23 int length = strlen( first );24 length = ( length < 25 ? length : 24 );25 strncpy( firstName, first, length );26 firstName[ length ] = '\0';2728 // copy last into lastName and be sure that it fits29 length = strlen( last );30 length = ( length < 25 ? length : 24 );31 strncpy( lastName, last, length );32 lastName[ length ] = '\0';3334 // output Employee object to show when constructor is called35 cout << "Employee object constructor: "36 << firstName << ' ' << lastName << endl;37

compiler使用預設的copyconstructor.

2003 Prentice Hall, Inc.All rights reserved.

Outline58

employee1.cpp(3 of 3)

38 } // end Employee constructor3940 // print Employee object41 void Employee::print() const42 {43 cout << lastName << ", " << firstName << "\nHired: ";44 hireDate.print();45 cout << " Birth date: ";46 birthDate.print();47 cout << endl;4849 } // end function print5051 // output Employee object to show when its destructor is called52 Employee::~Employee()53 {54 cout << "Employee object destructor: "55 << lastName << ", " << firstName << endl;5657 } // end destructor ~Employee

Page 30: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

30

2003 Prentice Hall, Inc.All rights reserved.

Outline59

fig07_10.cpp(1 of 1)

1 // Fig. 7.10: fig07_10.cpp2 // Demonstrating composition--an object with member objects.3 #include <iostream>45 using std::cout;6 using std::endl;78 #include "employee1.h" // Employee class definition910 int main()11 {12 Date birth( 7, 24, 1949 );13 Date hire( 3, 12, 1988 );14 Employee manager( "Bob", "Jones", birth, hire );1516 cout << '\n';17 manager.print();1819 cout << "\nTest Date constructor with invalid values:\n";20 Date lastDayOff( 14, 35, 1994 ); // invalid month and day21 cout << endl;2223 return 0;2425 } // end main

主程式實作主程式實作

沒有include “date.h” 為何可以用Date?

2003 Prentice Hall, Inc.All rights reserved.

Outline60

fig07_10.cppoutput (1 of 1)

Date object constructor for date 7/24/1949Date object constructor for date 3/12/1988Employee object constructor: Bob Jones

Jones, BobHired: 3/12/1988 Birth date: 7/24/1949

Test Date constructor with invalid values:Month 14 invalid. Set to month 1.Day 35 invalid. Set to day 1.Date object constructor for date 1/1/1994

Date object destructor for date 1/1/1994Employee object destructor: Jones, BobDate object destructor for date 3/12/1988Date object destructor for date 7/24/1949Date object destructor for date 3/12/1988Date object destructor for date 7/24/1949

建構物件

列印物件

宣稱Date物件

使用錯誤日期

解構物件

為何建構物件時只出現一次?

為何解構物件時會出現兩次date 3/12/1988與date 7/24/1949?

Page 31: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

31

2003 Prentice Hall, Inc. All rights reserved.

61

7.4 friend Functions and friend Classes

– 定義在類別內但不是類別的成員函式– 可存取類別的 non-public 成員– 宣稱 friends 函式的方法

• 將函式的prototype宣稱在類別定義中• 在函式的 prototype 前加入 keyword friend

• friend 函式

2003 Prentice Hall, Inc. All rights reserved.

62

7.4 friend Functions and friend Classes

• friend 類別– 如要讓ClassTwo的所有成員函式成為ClassOne的friend

• 將下行放入ClassOne的定義中friend class ClassTwo;

Page 32: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

32

2003 Prentice Hall, Inc. All rights reserved.

63

7.4 friend Functions and friend Classes

• 夥伴關係的特性– 必須在給予者類別中指定

• 如Class B若要成為 class A的夥伴– 則Class A必須指明class B為friend

– 非對稱性(Non-Symmetric)• Class B 是class A的 friend• Class A不一定是class B 的friend

– 無遞移性(Not transitive )• Class A是class B的friend• Class B是class C的friend• Class A不一定是Class C的friend

CACBBA

⇒⇒⇒

ABBA

⇒⇒

2003 Prentice Hall, Inc. All rights reserved.

64

friend Function使用範例

Page 33: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

33

2003 Prentice Hall, Inc.All rights reserved.

Outline65

fig07_11.cpp(1 of 3)

1 // Fig. 7.11: fig07_11.cpp2 // Friends can access private members of a class.3 #include <iostream>45 using std::cout;6 using std::endl;78 // Count class definition9 class Count {10 friend void setX( Count &, int ); // friend declaration1112 public:1314 // constructor15 Count()16 : x( 0 ) // initialize x to 017 {18 // empty body20 } // end Count constructor2122 // output x23 void print() const24 {25 cout << x << endl;27 } // end function print2829 private:30 int x; // data member32 }; // end class Count

2003 Prentice Hall, Inc.All rights reserved.

Outline66

fig07_11.cpp(2 of 3)

3334 // function setX can modify private data of Count35 // because setX is declared as a friend of Count36 void setX( Count &c, int val )37 {38 c.x = val; // legal: setX is a friend of Count3940 } // end function setX41

Page 34: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

34

2003 Prentice Hall, Inc.All rights reserved.

Outline67

fig07_11.cpp(3 of 3)

fig07_11.cppoutput (1 of 1)

42 int main()43 {44 Count counter; // create Count object4546 cout << "counter.x after instantiation: ";47 counter.print();4849 setX( counter, 8 ); // set x with a friend5051 cout << "counter.x after call to setX friend function: ";52 counter.print();5354 return 0;5556 } // end main

counter.x after instantiation: 0counter.x after call to setX friend function: 8

主程式實作主程式實作

輸出結果?

2003 Prentice Hall, Inc. All rights reserved.

68

non-friend Function範例

Page 35: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

35

2003 Prentice Hall, Inc.All rights reserved.

Outline69

fig07_12.cpp(1 of 3)

1 // Fig. 7.12: fig07_12.cpp2 // Non-friend/non-member functions cannot access3 // private data of a class.4 #include <iostream>56 using std::cout;7 using std::endl;89 // Count class definition10 // (note that there is no friendship declaration)11 class Count {1213 public:15 // constructor16 Count()17 : x( 0 ) // initialize x to 018 {19 // empty body21 } // end Count constructor2223 // output x24 void print() const25 {26 cout << x << endl;28 } // end function print2930 private:31 int x; // data member33 }; // end class Count

沒定義friend

2003 Prentice Hall, Inc.All rights reserved.

Outline70

fig07_12.cpp(2 of 3)

3435 // function tries to modify private data of Count,36 // but cannot because function is not a friend of Count37 void cannotSetX( Count &c, int val )38 {39 c.x = val;4041 } // end function cannotSetX4243 int main()44 {45 Count counter; // create Count object4647 cannotSetX( counter, 3 ); // cannotSetX is not a friend4849 return 0;5051 } // end main

會發生編譯錯誤

D:\cpphtp4_examples\ch07\Fig07_12\Fig07_12.cpp(39) : error C2248: 'x' : cannot access private member declared in class 'Count' D:\cpphtp4_examples\ch07\Fig07_12\Fig07_12.cpp(31) : see declaration of 'x'

Page 36: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

36

2003 Prentice Hall, Inc. All rights reserved.

71

7.5 Using the this Pointer

• this pointer– 指到物件本身記憶體位址– 不屬於物件,不是物件的資料成員– 呼叫物件的non-static成員函式時

• 編譯器會將this指標當成第一個參數傳入– 物件可使用或不使用this指標來存取物件的成員函式

2003 Prentice Hall, Inc. All rights reserved.

72

7.5 Using the this Pointer

• this指標的型別– 依所存取的成員函式是否為const而定– non-const member function of Employee

• this has type Employee * const– 指到物件位址的常數指標

– const member function of Employee• this has type const Employee * const

– 指到常數物件位址的常數指標

Page 37: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

37

2003 Prentice Hall, Inc. All rights reserved.

73

this指標使用範例1

2003 Prentice Hall, Inc.All rights reserved.

Outline74

fig07_13.cpp(1 of 3)

1 // Fig. 7.13: fig07_13.cpp2 // Using the this pointer to refer to object members.3 #include <iostream>45 using std::cout;6 using std::endl;78 class Test {910 public:11 Test( int = 0 ); // default constructor12 void print() const;1314 private:15 int x;1617 }; // end class Test18

類別定義類別定義

Page 38: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

38

2003 Prentice Hall, Inc.All rights reserved.

Outline75

fig07_13.cpp(2 of 3)

19 // constructor20 Test::Test( int value )21 : x( value ) // initialize x to value22 {23 // empty body2425 } // end Test constructor2627 // print x using implicit and explicit this pointers;28 // parentheses around *this required29 void Test::print() const30 {31 // implicitly use this pointer to access member x32 cout << " x = " << x;3334 // explicitly use this pointer to access member x35 cout << "\n this->x = " << this->x;3637 // explicitly use dereferenced this pointer and38 // the dot operator to access member x39 cout << "\n(*this).x = " << ( *this ).x << endl;4041 } // end function print42

類別實作類別實作

2003 Prentice Hall, Inc.All rights reserved.

Outline76

fig07_13.cpp(3 of 3)

fig07_13.cppoutput (1 of 1)

43 int main()44 {45 Test testObject( 12 );4647 testObject.print();4849 return 0;5051 } // end main

x = 12 this->x = 12(*this).x = 12

主程式主程式

執行結果

Page 39: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

39

2003 Prentice Hall, Inc. All rights reserved.

77

7.5 Using the this Pointer

• 使用this指標進行連續的成員函式呼叫– 使用相同指令呼叫多個函式– 函式傳回相同物件的參考指標

{ return *this; }– 其它函式使用該指標進行操作– 不傳回參考指標的函式只能在最後被呼叫

2003 Prentice Hall, Inc. All rights reserved.

78

this指標使用範例2

Page 40: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

40

2003 Prentice Hall, Inc.All rights reserved.

Outline79

time6.h (1 of 2)1 // Fig. 7.14: time6.h2 // Cascading member function calls.34 // Time class definition.5 // Member functions defined in time6.cpp.6 #ifndef TIME6_H7 #define TIME6_H89 class Time {1011 public:12 Time( int = 0, int = 0, int = 0 ); // default constructor1314 // set functions15 Time &setTime( int, int, int ); // set hour, minute, second16 Time &setHour( int ); // set hour17 Time &setMinute( int ); // set minute18 Time &setSecond( int ); // set second1920 // get functions (normally declared const)21 int getHour() const; // return hour22 int getMinute() const; // return minute23 int getSecond() const; // return second24

類別定義類別定義

2003 Prentice Hall, Inc.All rights reserved.

Outline80

time6.h (2 of 2)

25 // print functions (normally declared const)26 void printUniversal() const; // print universal time27 void printStandard() const; // print standard time2829 private:30 int hour; // 0 - 23 (24-hour clock format)31 int minute; // 0 - 5932 int second; // 0 - 593334 }; // end class Time3536 #endif

Page 41: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

41

2003 Prentice Hall, Inc.All rights reserved.

Outline81

time6.cpp (1 of 5)1 // Fig. 7.15: time6.cpp2 // Member-function definitions for Time class.3 #include <iostream>45 using std::cout;67 #include <iomanip>89 using std::setfill;10 using std::setw;1112 #include "time6.h" // Time class definition1314 // constructor function to initialize private data;15 // calls member function setTime to set variables;16 // default values are 0 (see class definition)17 Time::Time( int hr, int min, int sec )18 {19 setTime( hr, min, sec );2021 } // end Time constructor22

類別實作類別實作

2003 Prentice Hall, Inc.All rights reserved.

Outline82

time6.cpp (2 of 5)

23 // set values of hour, minute, and second24 Time &Time::setTime( int h, int m, int s )25 {26 setHour( h );27 setMinute( m );28 setSecond( s );2930 return *this; // enables cascading3132 } // end function setTime3334 // set hour value35 Time &Time::setHour( int h )36 {37 hour = ( h >= 0 && h < 24 ) ? h : 0;3839 return *this; // enables cascading4041 } // end function setHour42

Page 42: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

42

2003 Prentice Hall, Inc.All rights reserved.

Outline83

time6.cpp (3 of 5)

43 // set minute value44 Time &Time::setMinute( int m )45 {46 minute = ( m >= 0 && m < 60 ) ? m : 0;4748 return *this; // enables cascading4950 } // end function setMinute5152 // set second value53 Time &Time::setSecond( int s )54 {55 second = ( s >= 0 && s < 60 ) ? s : 0;5657 return *this; // enables cascading5859 } // end function setSecond6061 // get hour value62 int Time::getHour() const63 {64 return hour;6566 } // end function getHour67

2003 Prentice Hall, Inc.All rights reserved.

Outline84

time6.cpp (4 of 5)

68 // get minute value69 int Time::getMinute() const70 {71 return minute;7273 } // end function getMinute7475 // get second value76 int Time::getSecond() const77 {78 return second;7980 } // end function getSecond8182 // print Time in universal format83 void Time::printUniversal() const84 {85 cout << setfill( '0' ) << setw( 2 ) << hour << ":"86 << setw( 2 ) << minute << ":"87 << setw( 2 ) << second;8889 } // end function printUniversal90

Page 43: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

43

2003 Prentice Hall, Inc.All rights reserved.

Outline85

time6.cpp (5 of 5)

91 // print Time in standard format92 void Time::printStandard() const93 {94 cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 )95 << ":" << setfill( '0' ) << setw( 2 ) << minute96 << ":" << setw( 2 ) << second97 << ( hour < 12 ? " AM" : " PM" );9899 } // end function printStandard

2003 Prentice Hall, Inc.All rights reserved.

Outline86

fig07_16.cpp(1 of 2)

1 // Fig. 7.16: fig07_16.cpp2 // Cascading member function calls with the this pointer.3 #include <iostream>45 using std::cout;6 using std::endl;78 #include "time6.h" // Time class definition910 int main()11 {12 Time t;1314 // cascaded function calls15 t.setHour( 18 ).setMinute( 30 ).setSecond( 22 );1617 // output time in universal and standard formats18 cout << "Universal time: ";19 t.printUniversal();2021 cout << "\nStandard time: ";22 t.printStandard();2324 cout << "\n\nNew standard time: ";25

主程式主程式

Page 44: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

44

2003 Prentice Hall, Inc.All rights reserved.

Outline87

fig07_16.cpp(2 of 2)

fig07_16.cppoutput (1 of 1)

26 // cascaded function calls27 t.setTime( 20, 20, 20 ).printStandard();2829 cout << endl;3031 return 0;3233 } // end main

Universal time: 18:30:22Standard time: 6:30:22 PM

New standard time: 8:20:20 PM

為什麼可以這樣用?

t.setHour( 18 ).setMinute( 30 ).setSecond( 22 );

t.setHour( 18 )執行完後傳回t的指標,所以上式變成

t.setMinute( 30 ).setSecond( 22 );

同樣的, t.setHour( 18 )執行完後傳回t

t.setSecond( 22 );

2003 Prentice Hall, Inc. All rights reserved.

88

7.6 Dynamic Memory Management withOperators new and delete

• 動態記憶體管理– 控制記憶體的配置與釋放– 運算元

• new• delete• Include standard header <new>

Page 45: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

45

2003 Prentice Hall, Inc. All rights reserved.

89

7.6 Dynamic Memory Management withOperators new and delete

• new的主要工作– 配置適當大小的記憶體給物件

• 假如記憶體不夠傳回錯誤– 呼叫建構子– 傳回物件指標

2003 Prentice Hall, Inc. All rights reserved.

90

7.6 Dynamic Memory Management withOperators new and delete

• Example 1Time *timePtr;timePtr = new Time;

• Example 2double *ptr = new double( 3.14159 );Time *timePtr = new Time( 12, 0, 0 );

• Example 3int *gradesArray = new int[ 10 ];

Page 46: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

46

2003 Prentice Hall, Inc. All rights reserved.

91

7.6 Dynamic Memory Management withOperators new and delete

– 釋放記憶體– 所釋放的記憶體可供其它物件使用

• delete的主要工作

2003 Prentice Hall, Inc. All rights reserved.

92

7.6 Dynamic Memory Management withOperators new and delete

• Example 1delete timePtr;

• Example 2delete [ ] gradesArray;

Page 47: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

47

2003 Prentice Hall, Inc. All rights reserved.

93

7.7 static Class Members

– 相同類別的每個物件具有一份自己的資料成員– 例如:

• Time T1, T2;

• Non-static class variable

T1hour

minute

second

T2hour

minute

second

2003 Prentice Hall, Inc. All rights reserved.

94

7.7 static Class Members

– 相同類別的每個物件存取到相同的資料成員– 例如:

• Time T1, T2;

• Static class variable

T1hour

minutesecond

T2hour

minutesecond

Timestatic class variables

Page 48: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

48

2003 Prentice Hall, Inc. All rights reserved.

95

7.7 static Class Members

– 對所有物件只需使用一份資料– 類似global variables, 但只有class scope

• 相同類別中的物件才能存取– 初始化只做一次-檔案– 即使沒有物件存在也會存在– 可以是public, private or protected

• Static class variable

2003 Prentice Hall, Inc. All rights reserved.

96

7.7 static Class Members

• 存取 static class variables– public static variables

• 只能使用operator(::)存取 Employee::count

– private static variables• 如果類別的物件不存在

– 只能透過public static member function存取Employee::getCount()

Page 49: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

49

2003 Prentice Hall, Inc. All rights reserved.

97

7.7 static Class Members

• static member functions– 不能存取non-static 資料成員及成員函式– this pointer不能存取static functions

• static data members and static member functions的存在與物件無關

2003 Prentice Hall, Inc. All rights reserved.

98

Static data使用範例

Page 50: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

50

2003 Prentice Hall, Inc.All rights reserved.

Outline99

employee2.h (1 of 2)1 // Fig. 7.17: employee2.h2 // Employee class definition.3 #ifndef EMPLOYEE2_H4 #define EMPLOYEE2_H56 class Employee {78 public:9 Employee( const char *, const char * ); // constructor10 ~Employee(); // destructor11 const char *getFirstName() const; // return first name12 const char *getLastName() const; // return last name1314 // static member function15 static int getCount(); // return # objects instantiated1617 private:18 char *firstName;19 char *lastName;2021 // static data member22 static int count; // number of objects instantiated2324 }; // end class Employee2526 #endif

類別定義類別定義

2003 Prentice Hall, Inc.All rights reserved.

Outline100

employee2.h (2 of 2)

employee2.cpp(1 of 3)

1 // Fig. 7.18: employee2.cpp2 // Member-function definitions for class Employee.3 #include <iostream>45 using std::cout;6 using std::endl;78 #include <new> // C++ standard new operator9 #include <cstring> // strcpy and strlen prototypes1011 #include "employee2.h" // Employee class definition1213 // define and initialize static data member14 int Employee::count = 0;1516 // define static member function that returns number of17 // Employee objects instantiated18 int Employee::getCount()19 {20 return count;2122 } // end static function getCount

類別實作類別實作

Page 51: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

51

2003 Prentice Hall, Inc.All rights reserved.

Outline101

employee2.cpp(2 of 3)

2324 // constructor dynamically allocates space for25 // first and last name and uses strcpy to copy26 // first and last names into the object27 Employee::Employee( const char *first, const char *last )28 {29 firstName = new char[ strlen( first ) + 1 ];30 strcpy( firstName, first );3132 lastName = new char[ strlen( last ) + 1 ];33 strcpy( lastName, last );3435 ++count; // increment static count of employees3637 cout << "Employee constructor for " << firstName38 << ' ' << lastName << " called." << endl;3940 } // end Employee constructor41

2003 Prentice Hall, Inc.All rights reserved.

Outline102

employee2.cpp(3 of 3)

42 // destructor deallocates dynamically allocated memory43 Employee::~Employee()44 {45 cout << "~Employee() called for " << firstName46 << ' ' << lastName << endl;4748 delete [] firstName; // recapture memory49 delete [] lastName; // recapture memory5051 --count; // decrement static count of employees5253 } // end destructor ~Employee5455 // return first name of employee56 const char *Employee::getFirstName() const57 {58 // const before return type prevents client from modifying59 // private data; client should copy returned string before60 // destructor deletes storage to prevent undefined pointer61 return firstName;6263 } // end function getFirstName

Page 52: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

52

2003 Prentice Hall, Inc.All rights reserved.

Outline103

employee2.cpp(3 of 3)

6465 // return last name of employee66 const char *Employee::getLastName() const67 {68 // const before return type prevents client from modifying69 // private data; client should copy returned string before70 // destructor deletes storage to prevent undefined pointer71 return lastName;7273 } // end function getLastName

2003 Prentice Hall, Inc.All rights reserved.

Outline104

fig07_19.cpp(1 of 2)

1 // Fig. 7.19: fig07_19.cpp2 // Driver to test class Employee.3 #include <iostream>45 using std::cout;6 using std::endl;78 #include <new> // C++ standard new operator910 #include "employee2.h" // Employee class definition1112 int main()13 {14 cout << "Number of employees before instantiation is "15 << Employee::getCount() << endl; // use class name1617 Employee *e1Ptr = new Employee( "Susan", "Baker" );18 Employee *e2Ptr = new Employee( "Robert", "Jones" );1920 cout << "Number of employees after instantiation is "21 << e1Ptr->getCount();22

主程式主程式

Page 53: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

53

2003 Prentice Hall, Inc.All rights reserved.

Outline105

fig07_19.cpp(2 of 2)

23 cout << "\n\nEmployee 1: "24 << e1Ptr->getFirstName()25 << " " << e1Ptr->getLastName()26 << "\nEmployee 2: "27 << e2Ptr->getFirstName()28 << " " << e2Ptr->getLastName() << "\n\n";2930 delete e1Ptr; // recapture memory31 e1Ptr = 0; // disconnect pointer from free-store space32 delete e2Ptr; // recapture memory33 e2Ptr = 0; // disconnect pointer from free-store space3435 cout << "Number of employees after deletion is "36 << Employee::getCount() << endl;3738 return 0;3940 } // end main

2003 Prentice Hall, Inc.All rights reserved.

Outline106

fig07_19.cppoutput (1 of 1)

Number of employees before instantiation is 0Employee constructor for Susan Baker called.Employee constructor for Robert Jones called.Number of employees after instantiation is 2

Employee 1: Susan BakerEmployee 2: Robert Jones

~Employee() called for Susan Baker~Employee() called for Robert JonesNumber of employees after deletion is 0

Page 54: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

54

2003 Prentice Hall, Inc. All rights reserved.

107

7.8 Data Abstraction and InformationHiding

– 類別的功能描述與實作無關– 只需知道功能不用管如何作

• 資訊隱藏(Information hiding)– 隱藏類別的實作部份

• 資料抽象化(Data Abstraction)

2003 Prentice Hall, Inc. All rights reserved.

108

7.8 Data Abstraction and InformationHiding

• Example: 堆疊(stack)– PUSH:資料元素由頂部加入– POP:資料元素由頂部取出– 後進先出Last-in, first-out (LIFO)– 用戶只需知道LIFO方式

• 不用知道如何實作

Page 55: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

55

2003 Prentice Hall, Inc. All rights reserved.

109

7.8 Data Abstraction and InformationHiding

– 趨近真實世界的概念及行為模型– 資料表示

• 例:int, float是數字的模型– 不夠表示所有可能情形

– 資料運算

• C++具可擴充性– 不能改變標準資料型態– 但可自訂新的資料型態

• 抽象資料型態 (Abstract data types; ADTs)

2003 Prentice Hall, Inc. All rights reserved.

110

Example: Array Abstract Data Type

• 陣列資料抽象化– 不針對特定資料型態– Could include

• 註標(Subscript)範圍檢查• 任意範圍的註標(可不從0開始)• 陣列給值(Array assignment )• 陣列比較(Array comparison )• 陣列輸入輸出(Array input/output )• 能夠知道自己的大小(Arrays that know their sizes )• 可動態擴充陣列大小(Arrays that expand dynamically to

accommodate more elements)

Page 56: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

56

2003 Prentice Hall, Inc. All rights reserved.

111

Queue Abstract Data Type

• 佇列(Queue)– 先進先出(First in, first out : FIFO)– Enqueue

• 一次可放一個元素進入佇列內– Dequeue

• 一次可由佇列內取出一個元素

• 佇列抽象資料型態– 隱藏實作– 只有佇列成員函式可存取內部資料

2003 Prentice Hall, Inc. All rights reserved.

112

7.9 Container Classes and Iterators

• 容器類別(Container classes; collection classes)– 設計用來存放物件– 一般功能

• 插入,刪除,搜尋,排序,或檢查容器內的項目– Examples

• Arrays, stacks, queues, trees and linked lists

Page 57: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

57

2003 Prentice Hall, Inc. All rights reserved.

113

7.9 Container Classes and Iterators

• Iterator物件 (iterators)– 傳回容器內的下個項目

• 或對容器內的下個項目做特定處理– 一個容器可有多個 iterators

• 每個iterator可記錄自己的位置

2003 Prentice Hall, Inc. All rights reserved.

114

7.10 Proxy Classes

• 代理類別(Proxy class)– 隱藏另一個類別的實作內容– 只知道被隱藏類別的 public 介面– 可供使用者使用類別的服務,而看不到類別的設計

實作類別代理類別使用者

Page 58: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

58

2003 Prentice Hall, Inc. All rights reserved.

115

7.10 Proxy Classes

• 前置類別宣稱(Forward class declaration)– 避免在代理類別內引用標頭檔– 參考實作類別前必須先宣稱類別– Format:

class ClassToLoad;

2003 Prentice Hall, Inc. All rights reserved.

116

Proxy class使用範例

Page 59: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

59

2003 Prentice Hall, Inc.All rights reserved.

Outline117

implementation.h(1 of 2)

1 // Fig. 7.20: implementation.h2 // Header file for class Implementation34 class Implementation {56 public:78 // constructor9 Implementation( int v )10 : value( v ) // initialize value with v11 {12 // empty body1314 } // end Implementation constructor1516 // set value to v17 void setValue( int v )18 {19 value = v; // should validate v2021 } // end function setValue22

實作類別定義實作類別定義

2003 Prentice Hall, Inc.All rights reserved.

Outline118

implementation.h(2 of 2)

23 // return value24 int getValue() const25 {26 return value;2728 } // end function getValue2930 private:31 int value;3233 }; // end class Implementation

Page 60: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

60

2003 Prentice Hall, Inc.All rights reserved.

Outline119

interface.h (1 of 1)1 // Fig. 7.21: interface.h2 // Header file for interface.cpp34 class Implementation; // forward class declaration56 class Interface {78 public:9 Interface( int );10 void setValue( int ); // same public interface as11 int getValue() const; // class Implementation12 ~Interface();1314 private:1516 // requires previous forward declaration (line 4)17 Implementation *ptr;1819 }; // end class Interface

介面類別定義介面類別定義

2003 Prentice Hall, Inc.All rights reserved.

Outline120

interface.cpp(1 of 2)

1 // Fig. 7.22: interface.cpp2 // Definition of class Interface3 #include "interface.h" // Interface class definition4 #include "implementation.h" // Implementation class definition56 // constructor7 Interface::Interface( int v )8 : ptr ( new Implementation( v ) ) // initialize ptr9 {10 // empty body1112 } // end Interface constructor1314 // call Implementation's setValue function15 void Interface::setValue( int v )16 {17 ptr->setValue( v );1819 } // end function setValue20

介面類別實作介面類別實作

建立實作物件

Page 61: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

61

2003 Prentice Hall, Inc.All rights reserved.

Outline121

interface.cpp(2 of 2)

21 // call Implementation's getValue function22 int Interface::getValue() const23 {24 return ptr->getValue();2526 } // end function getValue2728 // destructor29 Interface::~Interface()30 {31 delete ptr;3233 } // end destructor ~Interface

釋放相對應的實作類別物件

2003 Prentice Hall, Inc.All rights reserved.

Outline122

fig07_23.cpp(1 of 1)

fig07_23.cppoutput (1 of 1)

1 // Fig. 7.23: fig07_23.cpp2 // Hiding a class’s private data with a proxy class.3 #include <iostream>45 using std::cout;6 using std::endl;78 #include "interface.h" // Interface class definition910 int main()11 {12 Interface i( 5 );1314 cout << "Interface contains: " << i.getValue()15 << " before setValue" << endl;1617 i.setValue( 10 );1819 cout << "Interface contains: " << i.getValue()20 << " after setValue" << endl;2122 return 0;2324 } // end main

Interface contains: 5 before setValueInterface contains: 10 after setValue

介面類別實作介面類別實作

只需引用代理類別的標頭檔

Page 62: Ꝁ띾ꑀ뮡ꧺ - 南華大學CSIE/ycliaw/OOP/07_Classes2.pdf1 2003 Prentice Hall, Inc. All rights reserved. 1 띾ꑀ뮡 2003 Prentice Hall, Inc. All rights reserved. Outline 2

62

2003 Prentice Hall, Inc. All rights reserved.

123

使用代理類別,使用代理類別,

主程式看不到實作類別的標頭檔定義主程式看不到實作類別的標頭檔定義

資料隱藏效果更好資料隱藏效果更好

2003 Prentice Hall, Inc. All rights reserved.

124

Chapter 7: Classes Part II

Outline7.1 Introduction7.2 const (Constant) Objects and const Member Functions7.3 Composition: Objects as Members of Classes7.4 friend Functions and friend Classes7.5 Using the this Pointer7.6 Dynamic Memory Management with Operators new and delete7.7 static Class Members7.8 Data Abstraction and Information Hiding7.9 Container Classes and Iterators7.10 Proxy Classes