http www csie nctu edu twtsaiwncpp 02ooaood ppt

  • Slides: 92
Download presentation
http: //www. csie. nctu. edu. tw/~tsaiwn/cpp/ 02_ooa_ood. ppt C++物件導向程式設計 Introduction to C++ with OOP

http: //www. csie. nctu. edu. tw/~tsaiwn/cpp/ 02_ooa_ood. ppt C++物件導向程式設計 Introduction to C++ with OOP 蔡文能 tsaiwn@csie. nctu. edu. tw tsaiwn@cs. nctu. edu. tw 交通大學資訊 程學系 2007/07/24 1 交通大學資訓 程學系 蔡文能

Agenda Review : How to design/construct/use a Stack? • • • Introduction to OOA,

Agenda Review : How to design/construct/use a Stack? • • • Introduction to OOA, OOD, and UML Inheritance and examples: Animal and Mankind, Deque and Stack/Queue, Vector and Stack virtual function and Polymorphism: How it works? Next: • Generic programming: template function/class, and STL • Exceptions: Scope of exceptions, raising exception, exception handlers • More tips about class and ADT: a. constructor/Destructor, b. class members vs. instance members, c. friend access control of class members 2 交通大學資訓 程學系 蔡文能

Object Oriented Concept OOA, OOD, OOP Review OO Analysis OO Design 3 交通大學資訓 程學系

Object Oriented Concept OOA, OOD, OOP Review OO Analysis OO Design 3 交通大學資訓 程學系 蔡文能

OO features ü Encapsulation ü Information Hiding The concept of abstraction is 抽象化的概念以前 就有:

OO features ü Encapsulation ü Information Hiding The concept of abstraction is 抽象化的概念以前 就有: 函數/副程式 增加: ü Inheritance ü Polymorphism fundamental in programming u. Subprogram / function Ø process abstraction u. ADT Ø Data abstraction Software Reuse 4 交通大學資訓 程學系 蔡文能

Class vs. Object • Object is an instance of some class – int x;

Class vs. Object • Object is an instance of some class – int x; float yy; // int 與 float 也是類別(type = class) • Object(物件, 個體, 東西) -- 就是以前所謂的變數 class Student { long sid; char name[9]; // … }; Student 是 class (類別) 這些是 Object Student x, y[99], chang 3; 5 交通大學資訓 程學系 蔡文能

Access control of class members #include<iostream> class Student{ // private: long sid; char name[9];

Access control of class members #include<iostream> class Student{ // private: long sid; char name[9]; }; Student x, y[99], tempstu; int main( ) { x. sid = 38; // Error! cout << x. sid; // Error! } #include<iostream> Default is private: Default is public: struct Student{ // public: long sid; char name[9]; }; Student x, y[99], tempstu; int main( ) { x. sid = 38; // OK! cout << x. sid; // OK! } 6 交通大學資訓 程學系 蔡文能

Struct vs. Class (1/3) #include <iostream. h> class Student { // 若在此寫 public: ?

Struct vs. Class (1/3) #include <iostream. h> class Student { // 若在此寫 public: ? long sid; // default is private for class }; // default is public for struct int main( ) { Student x; x. sid = 123; // compile錯, access not allowed cout << "== " << x. sid << endl; // compile錯 return 0; } 若改為 struct Student 則變沒錯! Why? 7 交通大學資訓 程學系 蔡文能

Struct vs. Class (2/3) 可以稱朋友 : 耍特權 #include <iostream. h> class Student { long

Struct vs. Class (2/3) 可以稱朋友 : 耍特權 #include <iostream. h> class Student { long sid; // default is private for class friend int main( ); // 解除 access control }; // default is public for struct int main( ) { Student x; x. sid = 123; // 變對了 cout << "==" << x. sid << endl; // compile OK return 0; } C++ Joke: Friend is the only one who can touch your private 交通大學資訓 程學系 蔡文能 ! 8

Struct vs. Class (3/3) 正確概念是透過 #include <iostream. h> member functions class Student { //

Struct vs. Class (3/3) 正確概念是透過 #include <iostream. h> member functions class Student { // private: long sid; public: show. Number( ) { return sid; } set. Id( long xx) { sid = xx; } }; int main( ) { Student x, y; x. set. Id(123); // OK, 透過 public function set. Id( ) cout << "==" << x. show. Number( ) << endl; // OK return 0; } 交通大學資訓 程學系 蔡文能 9

O O Features • Encapsulation • Information Hiding (Data Hiding) • Inheritance • Polymorphism

O O Features • Encapsulation • Information Hiding (Data Hiding) • Inheritance • Polymorphism Object Oriented ( 物件導向 ) ( 個體導向 ) 交通大學資訓 程學系 蔡文能 Object Based For Software Reuse 10

OO tools • There are many OO tools for Software Engineering (軟體 程) •

OO tools • There are many OO tools for Software Engineering (軟體 程) • OOA – CRC cards (Class-Responsibility-Collaborator) • OOD – Class diagram, UML, Rational ROSE, … • OOP – Languages support OOP: C++, Java, Ada, … 11 交通大學資訓 程學系 蔡文能

OOA: CRC Cards • Step two: Write CRC cards and work through scenarios –

OOA: CRC Cards • Step two: Write CRC cards and work through scenarios – Class-Responsibility-Collaborator Cards (Cunningham and Beck) – Just 3 x 5 cards • Although CRC is not part of UML, they add some very useful insights throughout a development. Data fields (attributes) 寫在背面 交通大學資訓 程學系 蔡文能 12

OOD: Object-Oriented Design • Step one: Create a UML class diagram of your objects

OOD: Object-Oriented Design • Step one: Create a UML class diagram of your objects • Step two: Create a detailed description of the services to be performed – Peter Coad's "I am a Count. I know how to increment…" – Activity, sequence, or collaboration UML diagrams 13 交通大學資訓 程學系 蔡文能

Façade Design Pattern • Façade: defines a clean, high-level interface to a subsystem. •

Façade Design Pattern • Façade: defines a clean, high-level interface to a subsystem. • Context: building easy-to-use and maintain subsystems • Problem: Each class in the subsystem provides part of the subsystem’s functionality, clients has to know the inside, changes to the subsystem may require changes to the clients. • Solution: Add an interface class (the façade class) that knows the structure of the subsystem and forwards requests… • Consequences: no or less dependency of client from structure of subsystem, ideal for layered subsystems Facade 14 交通大學資訓 程學系 蔡文能

MDA-Model Driven Architecture? • A New Way to Specify and Build Systems – 2001年由OMG制定的新開發架構

MDA-Model Driven Architecture? • A New Way to Specify and Build Systems – 2001年由OMG制定的新開發架構 (http: //www. omg. org) – 以UML Model(塑模)為基礎 – 支援完整開發週期: Analysis, Design, Implementation, Deployment, Maintenance, Evolution & Integration with later systems (改進與後續整合) – 內建協同運作性及跨平台性 – 降低開發初期成本及提高ROI (投資報酬) – 可套用至你所使用的任何環境: • Programming language Network • Operating System Middleware 15 交通大學資訓 程學系 蔡文能

Unified Modeling Language http: //www. omg. org http: //www. UML. org • There have

Unified Modeling Language http: //www. omg. org http: //www. UML. org • There have been O-O gurus for many years • Three of them worked together to define UML (“Three amigos”: Booch, Rumbaugh, Jacobson) • Has now been approved as a standard by the Object Management Group (OMG) • Very powerful, many forms of notation – It's even provable! (with OCL) (Object Constrain Language) amigos = friends 交通大學資訓 程學系 蔡文能 16

So, What is UML? 軟體 程師共通的語言 • UML is a Unified Modeling Language •

So, What is UML? 軟體 程師共通的語言 • UML is a Unified Modeling Language • UML is a set of notations, not a single methodology • Modeling is a way of thinking about the problems using models organized around the real world ideas. • Resulted from the convergence of notations from three leading Object-Oriented methods: • Booch method (by Grady Booch) • OMT (by James Rumbaugh) • OOSE (by Ivar Jacobson) • You can model 80% of most problems by using about 20% of the UML is a “blueprint” for building complex soft 17 交通大學資訓 程學系 蔡文能

History of the UML( http: //www. uml. org/ ) Public Feedback Approved 2004 UML

History of the UML( http: //www. uml. org/ ) Public Feedback Approved 2004 UML 2. 0 Minor revision 2003 UML 1. 5 Minor revision 2001 UML 1. 4 Minor revision 1999 UML 1. 3 OMG Acceptance, Nov 1997 Final submission to OMG, Sept 1997 First submission to OMG, Jan 1997 UML 1. 1 UML partners UML 1. 0 Web - June 1996 UML 0. 9 OOPSLA 95 Other 交通大學資訓 程學系 蔡文能methods Unified Method 0. 8 OOSEBooch method OMT 18

UML 常用的 Diagrams • Use case diagrams – Functional behavior of the system as

UML 常用的 Diagrams • Use case diagrams – Functional behavior of the system as seen by the user. • Class diagrams – Static structure of the system: Objects, Attributes, and Associations. • Activity diagrams – Dynamic behavior of a system, in particular the workflow, i. e. a flowchart. • Sequence diagrams – Dynamic behavior between actors and system objects. • Statechart diagrams – Dynamic behavior of an individual object as FSM (有限狀態機). 19 交通大學資訓 程學系 蔡文能

UML 12 Diagrams • Behavior : – Use Case – Sequence – Collaboration –

UML 12 Diagrams • Behavior : – Use Case – Sequence – Collaboration – State Chart – Activity • Structural: – Class – Component – Deployment – Object • Model Management: – Packages (class diagram contains packages) – Subsystems (class diagram contains subsystems) – Models (class diagram contains models) 20 交通大學資訓 程學系 蔡文能

UML Core Conventions • Rectangles are classes or instances • Ovals are functions or

UML Core Conventions • Rectangles are classes or instances • Ovals are functions or use cases • Types are denoted with non-underlined names ü Simple. Watch ü Firefighter • Instances are denoted with an underlined names ü my. Watch: Simple. Watch ü Joe: Firefighter • Diagrams are higraphs Higraphs are an extension to the familiar Directed Graph structure where nodes are connected by edges to other nodes. Nodes represent entities in some domain (in our case, classes, packages, methods, etc. ). – Nodes are entities (e. g. classes, states) – Arcs are relationships among entities (e. g. sender/receiver) – Containment represents belonging (e. g. use cases in package) 21 交通大學資訓 程學系 蔡文能

Use Case Diagram examples Package Simple. Watch Actor A use case documents the interaction

Use Case Diagram examples Package Simple. Watch Actor A use case documents the interaction between the system user and the system. It is highly detailed in describing what is required but is free of most implementation details and constraints. Read. Time Watch. User Use case Set. Time Watch. Repair. Person Change. Battery Use case diagrams represent the functionality of the system from user’s point of view. (強調 what, 但暫不管 how) 22 交通大學資訓 程學系 蔡文能

Class Diagram : a simple Watch Class Multiplicity 1 1 2 Push. Button state

Class Diagram : a simple Watch Class Multiplicity 1 1 2 Push. Button state push() release() Association Simple. Watch LCDDisplay blink. Idx blink. Seconds() blink. Minutes() blink. Hours() stop. Blinking() referesh() Attributes 1 1 1 2 Battery load() 1 Time now() Operations Class diagrams represent the structure of the domain or system 23 交通大學資訓 程學系 蔡文能

Object : Watch. User Sequence Diagram : Simple. Watch press. Button 1() : LCDDisplay

Object : Watch. User Sequence Diagram : Simple. Watch press. Button 1() : LCDDisplay : Time blink. Hours() blink. Minutes() press. Button 2() increment. Minutes() refresh() press. Buttons 1 And 2() Activation commit. New. Time() stop. Blinking() Activation Message Sequence diagrams represent the behavior as interactions It shows sequence of events for a particular use case Object diagram with numbered messages Sequence numbers of messages are nested by procedure call Collaboration Diagram 交通大學資訓 程學系 蔡文能 24

State chart Diagrams for the watch Event State Initial state button 1&2 Pressed Increment

State chart Diagrams for the watch Event State Initial state button 1&2 Pressed Increment Hours button 1 Pressed Transition button 1&2 Pressed button 2 Pressed Blink Hours Blink Minutes button 2 Pressed Increment Minutes button 1 Pressed button 1&2 Pressed Blink Seconds Stop Blinking Final state 交通大學資訓 程學系 蔡文能 button 2 Pressed Increment Seconds FSM: Finite State Machine 25

Activity Diagrams • An activity diagram shows flow control within a system • An

Activity Diagrams • An activity diagram shows flow control within a system • An activity diagram is a special case of a state chart diagram in which states are activities (“functions”) • Two types of states: – Action state: • Cannot be decomposed any further • Happens “instantaneously” with respect to the level of abstraction used in the model – Activity state: • Can be decomposed further • The activity is modeled by another activity diagram 描述Business process或use case的操作流程; 像流程圖 交通大學資訓 程學系 蔡文能 26

Classes in UML • Classes describe objects – Behaviour (member function signature / implementation)

Classes in UML • Classes describe objects – Behaviour (member function signature / implementation) – Properties (attributes and associations) – Association, aggregation, dependency, and inheritance relationships – Multiplicity and navigation indicators – Role names • Objects described by classes collaborate – Class relations → object relations – Dependencies between classes 27 交通大學資訓 程學系 蔡文能

UML Class Visibility shown as + public private # protected Class name Data members

UML Class Visibility shown as + public private # protected Class name Data members (attributes) Instance methods Class method (static) Arguments Return types Data members, arguments and methods are specified by visibility name : type 交通大學資訓 程學系 蔡文能 28

Class Attributes are the instance data members and class data members Class data members

Class Attributes are the instance data members and class data members Class data members (underlined) are shared between all instances (objects) of a given class Class name Attribute compartment Data types shown after ": " Visibility shown as + public private # protected visibility name : type 29 交通大學資訓 程學系 蔡文能

Class Operations (Interface) Operations are the class methods with their argument and return types

Class Operations (Interface) Operations are the class methods with their argument and return types Public (+) operations define the class interface Class methods (underlined) can only access to class data members, no need for a class instance (object) Operations compartment 30 交通大學資訓 程學系 蔡文能

Template Classes Type parameter(s) Operations compartment as usual, but may have type parameter instead

Template Classes Type parameter(s) Operations compartment as usual, but may have type parameter instead of concrete type Generic classes depending on parametrised types 31 交通大學資訓 程學系 蔡文能

Class Inheritance Base class or super class Arrow shows direction of dependency (B inherits

Class Inheritance Base class or super class Arrow shows direction of dependency (B inherits A) Derived class or subclass → → → 交通大學資訓 程學系 蔡文能 B inherits A's interface, behaviour and data members B can extend A, i. e. add new data members or member functions B depends on A, A knows nothing about B 32

Multiple Inheritance (Java) The derived class inherits interface, behaviour and data members of all

Multiple Inheritance (Java) The derived class inherits interface, behaviour and data members of all its base classes implements extends Extension and overriding works as before B implements the interface A and is also a "countable" class since it inherits class Countable class B extends Countable implements A { /*…*/ } 交通大學資訓 程學系 蔡文能 33

A is associated with B • • A has a B A has a

A is associated with B • • A has a B A has a method that returns a B vice versa etc. 34 交通大學資訓 程學系 蔡文能

Class Friendship Friends are granted access to private data members and member functions Friendship

Class Friendship Friends are granted access to private data members and member functions Friendship is given to other classes, never taken Friendship breaks data hiding, use carefully ! Friend is the only one who can touch your private! 交通大學資訓 程學系 蔡文能 35

Recommended Book: UML Distilled • Serious O-O designers DO use UML • UML Distilled

Recommended Book: UML Distilled • Serious O-O designers DO use UML • UML Distilled by Martin Fowler is a great practical introduction to UML • Official UML book series published by Addison-Wesley http: //www. omg. org 36 交通大學資訓 程學系 蔡文能

UML Tools • Most complete tool: Rational Rose, http: //www. rational. com • Lots

UML Tools • Most complete tool: Rational Rose, http: //www. rational. com • Lots of others : – Together by Object International, – Borland Together 2006 http: //www. togethersoft. com – BOOST (Basic Object-Oriented Support Tool) by Noel Rappin, available on CD/Co. Web – Argo-UML, Object. Plant, Posiden, etc. 37 交通大學資訓 程學系 蔡文能

Other O-O Languages (1/2) • Java == C++--++ – Similar to C++, except: •

Other O-O Languages (1/2) • Java == C++--++ – Similar to C++, except: • All user-defined types are classes • All objects are allocated from the heap and accessed through reference variables, including Arrays • Individual entities in classes have access control modifiers (private or public), rather than clauses • All inheritances are public; all functions are virtual except final • No operator overloading; No destructor; No pointer type • Java has a second scoping mechanism, package scope, which can be used in place of friends – All entities in all classes in a package that do not have access control modifiers are visible throughout the package 38 交通大學資訓 程學系 蔡文能

Other O-O Languages (2/2) • C# (唸作 C-Sharp, by Micro. Soft) – – –

Other O-O Languages (2/2) • C# (唸作 C-Sharp, by Micro. Soft) – – – Based on C++ and Java Adds two access modifiers, internal and protected internal All class instances are heap dynamic (same as in Java) Default constructors are available for all classes Garbage collection is used for most heap objects, so destructors are rarely used – structs are lightweight classes that do not support inheritance – Common solution to need for access to data members: accessor methods (getter and setter) – C# provides properties as a way of implementing getters and setters without requiring explicit method calls 39 交通大學資訓 程學系 蔡文能

Inheritance (繼承, 擴充) (1/3) class Animal{ long height; protected: double hehe; public: float weight;

Inheritance (繼承, 擴充) (1/3) class Animal{ long height; protected: double hehe; public: float weight; void jump( ) { /** … **/ } }; class Mankind : public Animal { long iq; public: void jump( ) { /** override **/ } void talk( ) { /** new **/ } }; int main( ) { Animal x; Mankind y; x. jump( ); cout << sizeof(x)<<endl; cout << sizeof(y)<<endl; y. jump( ); y. talk( ); } In C++, "; " is required to terminate a class 交通大學資訓 程學系 蔡文能 40

Inheritance (2/3) Ø Inheritance lets us create new classes from existing classes Ø Single

Inheritance (2/3) Ø Inheritance lets us create new classes from existing classes Ø Single inheritance: New class derived from one base class Ø Multiple inheritance: New class derived from more than one base class (may cause problems) Ø General syntax to define a derived class: Class class. Name: member. Access. Specifier base. Class. Name { // member list … } Ø member. Access. Specifier can be public, protected and private Ø If no member. Access. Specifier, it is a private inheritance 41 交通大學資訓 程學系 蔡文能

Inheritance (3/3) Protected Members of a Class Ø The protected members of a class

Inheritance (3/3) Protected Members of a Class Ø The protected members of a class can be accessed by not only the other members inside the class, but also the members in its derived classes Ø The protected members cannot be accessed outside the class Ø If member. Access. Specifier is public, all the members of the base class keep their access rights in the derived class Ø If member. Access. Specifier is protected, the public members of the base class become protected in the derived class, but the protected and private keep no change Ø If member. Access. Specifier is private, all the members of the base class become private in the derived class 若沒有繼承, 則寫 protected 與 private 完全相同 交通大學資訓 程學系 蔡文能 42

How can two classes be related? Inherits, Contains, Talks. To • Generalization-specialization or Is.

How can two classes be related? Inherits, Contains, Talks. To • Generalization-specialization or Is. A – Named. Box Is. A Box – Diagram: Triangle on the relationship line (參考前面 UML ) • Association or Has. A – Box Has. A Pen – Diagram: Just a relationship line (參考前面 UML ) – Aggregation is a part-whole relationship • Diagram: Diamond on the line (參考前面 UML ) • Dependency or Talks. To – Dependency is sort of temporary Has. A • Diagram: Dashed line in UML (參考前面 UML ) 43 交通大學資訓 程學系 蔡文能

(C++) Mankind inherits Animal Classes can be in same file class Animal { int

(C++) Mankind inherits Animal Classes can be in same file class Animal { int height = 0; int weight = 0; public: void talk( ) { printf("Won"); } }; public 繼承 class Mankind : public Animal { private: int iq = 120; public: void talk( ) { printf("Hello"); } }; /* 分號不能省掉 */ In C++, "; " is required to terminate a class 交通大學資訓 程學系 蔡文能 44

(Java) Mankind extends Animal Should be in different files public class Animal { private

(Java) Mankind extends Animal Should be in different files public class Animal { private int height = 0; private int weight = 0; public void talk( ) { System. out. println(“Arhh"); } } 不 要 管 文 法 public class Mankind extends Animal { private int iq = 120; public void talk( ) { System. out. println("Hello"); } } Mankind is-a Animal One Java file can only have one public class 45 交通大學資訓 程學系 蔡文能

manlib. h #ifndef __MANLIB__ #define __MANLIB__ class animal { // 建議大寫開頭: class Animal {

manlib. h #ifndef __MANLIB__ #define __MANLIB__ class animal { // 建議大寫開頭: class Animal { int pv 1; float pv 2; protected: int pt 1[5]; public: animal(int = 38); // default parameter float pb 1; int pb 2[9]; void talk(void); }; class Mankind: public animal { char * pv 3; public: Mankind(char * ="No. Name"); // Constructor with default 參數 ~Mankind( ); // Destructor int pb 3[8]; void talk(void); }; #endif 交通大學資訓 程學系 蔡文能 46

manlib. cpp (1/2) // Implementation file for "animal" and "Mankind" #include <stdio. h> #include

manlib. cpp (1/2) // Implementation file for "animal" and "Mankind" #include <stdio. h> #include <iostream> //#include <iostream. h> // 舊的C++ 用 iostream. h using namespace std; // 舊的C++不能用 namespace #include "manlib. h" animal: : animal(int x) { // constructor pv 1=x; pv 2=45. 67; this->pb 1=135. 246; for (int i=0; i<9; i++) pb 2[i]=i+1; //pb 2={ 1, 2, 3, 4, 5, 6, 7 , 8, 9}; cout<<" Animal shows upn"; }; void animal: : talk(void) { cout << " animal talk, pv 1=" << dec <<pv 1 <<"=0 x" << hex << pv 1 <<"n"; cout << " t pv 2=" << pv 2 <<"n"; cout << " t pb 1=" << pb 1 <<"n"; cout << " t pb 2[6]=" << pb 2[6] <<"n"; }; 47 交通大學資訓 程學系 蔡文能

manlib. cpp (2/2) Mankind: : Mankind(char * name){ pv 3=name; cout << " Mankind

manlib. cpp (2/2) Mankind: : Mankind(char * name){ pv 3=name; cout << " Mankind "<< pv 3 << " appearsn"; } Mankind: : ~Mankind(void){ cout << " %%% Mankind "<< this->pv 3 << " is dying n"; } void Mankind: : talk(void) { // cout << " Mankind talk, pv 1=" << pv 1 <<"n"; // cout << " Mankind talk, pb 2=" << pb 2 <<"n"; // cout << " Mankind talk, pb 2=" << animal: : pb 2 <<"n"; cout << " Mankind talk, pb 2[0]=" << pb 2[0] <<"n"; cout << " Mankind talk, pv 3=" << pv 3 <<"n"; cout << " Mankind talk, pb 3[3]=" << pb 3[3] <<"n"; }; 48 交通大學資訓 程學系 蔡文能

Using Mankind 與 animal (mannew. cpp) #include <stdio. h> #include <iostream> // 注意 //

Using Mankind 與 animal (mannew. cpp) #include <stdio. h> #include <iostream> // 注意 // #include <iostream. h> #define call #include "manlib. h" // 舊的C++不能用 Using namespace std; animal aa 1(123), aa 2(456); Mankind * mm 1, *mm 2; void onlyasub(void) { Mankind nobody; cout << " Now in routine onlyasubn"; } main( ) { aa 1. talk(); cout << "Welcome to C++n"; call onlyasub(); mm 1= new Mankind("Chang-3"); mm 2= new Mankind("Lee-4"); cout << "mm 1 ->pb 1= " << mm 1 ->pb 1 << endl; cout << " (Let mm 1 talk)n"; mm 1 ->talk( ); delete mm 2; cout << " (and then Let mm 1 talk" << " by animal method)n"; mm 1 ->animal: : talk( ); return(0); } 49 交通大學資訓 程學系 蔡文能

Using Mankind 與 animal (mannew. cpp) #include <stdio. h> #include <iostream> // 舊版 C++

Using Mankind 與 animal (mannew. cpp) #include <stdio. h> #include <iostream> // 舊版 C++ 用 #include <iostream. h> #define call #include "manlib. h" using namespace std; // 舊版 C++ 不認識這 namespace statement animal aa 1(123), aa 2(456); Mankind * mm 1, *mm 2; void onlyasub(void) { Mankind nobody; cout << " Now in routine onlyasubn"; } main(){ aa 1. talk(); cout << "Welcome to C++n"; call onlyasub(); mm 1= new Mankind("Chang-3"); mm 2= new Mankind("Lee-4"); cout << "mm 1 ->pb 1=" << mm 1 ->pb 1 << "n"; cout << " (Let mm 1 talk)n"; mm 1 ->talk( ); delete mm 2; cout << " (and then Let mm 1 talk by animal method)n"; mm 1 ->animal: : talk( ); return(0); 交通大學資訓 程學系 蔡文能 } 50

Test class Mankind animal g++ -c manlib. cpp g++ mannew. cpp manlib. o. /a.

Test class Mankind animal g++ -c manlib. cpp g++ mannew. cpp manlib. o. /a. out Animal shows up animal talk, pv 1=123=0 x 7 b pv 2=45. 67 pb 1=135. 246 pb 2[6]=7 Welcome to C++ Animal shows up Mankind No. Name appears Now in routine onlyasub %%% Mankind No. Name is dying Animal shows up Mankind Chang-3 appears Animal shows up Mankind Lee-4 appears mm 1 ->pb 1=135. 246 注意比對 running result 與 程式碼! (Let mm 1 talk) Mankind talk, pb 2[0]=1 Mankind talk, pv 3=Chang-3 Mankind talk, pb 3[3]=0 %%% Mankind Lee-4 is dying (and then Let mm 1 talk by animal method) animal talk, pv 1=38=0 x 26 pv 2=45. 67 pb 1=135. 246 pb 2[6]=7 51 交通大學資訓 程學系 蔡文能

問題與思考: inherit == extend class 豪華鬧鐘 : public 鬧鐘 { // …豪華鬧鐘 is_a 鬧鐘

問題與思考: inherit == extend class 豪華鬧鐘 : public 鬧鐘 { // …豪華鬧鐘 is_a 鬧鐘 }; class Stack : private Deque { // … }; class Stack { Deque x; // … }; class Stack : public Vector { // … }; class Stack { Vector x; // … }; 52 交通大學資訓 程學系 蔡文能

http: //www. csie. nctu. edu. tw/~tsaiwn/cpp/ Take a Break 12 minutes 不要走開! tsaiwn@cs. nctu.

http: //www. csie. nctu. edu. tw/~tsaiwn/cpp/ Take a Break 12 minutes 不要走開! tsaiwn@cs. nctu. edu. tw 蔡文能 53 交通大學資訓 程學系 蔡文能

Multiple Inheritance ? Vehicle Person Doctor Surgeon Nurse Family Doctor Land Vehicle Car Amphibious

Multiple Inheritance ? Vehicle Person Doctor Surgeon Nurse Family Doctor Land Vehicle Car Amphibious Vehicle Boat 單一繼承 Java 不可 多重繼承; 但可多重 implements Water Vehicle 多重繼承 Multiple inheritance is powerful, but can cause ambiguity problems ØIf both base classes have functions of the same name ØSolution: specify exact function/data using : : my. Object. Base. Class 1: : function( ) Another Problem? 源自 vehicle 的資料會有兩份 Solution? 用 virtual 繼承 交通大學資訓 程學系 蔡文能 54

Multiple Inheritance and virtual Base Classes (1/3) • Ambiguities from multiple inheritance ios ostream

Multiple Inheritance and virtual Base Classes (1/3) • Ambiguities from multiple inheritance ios ostream iostream • iostream could have duplicate subobjects – Data from ios inherited into ostream and istream – Upcasting iostream pointer to ios object is a problem • Two ios subobjects could exist, which is used? – Ambiguous, may result in syntax error • iostream does not actually have this problem 55 交通大學資訓 程學系 蔡文能

Multiple Inheritance and virtual Base Classes (2/3) • Solution: use virtual base class inheritance

Multiple Inheritance and virtual Base Classes (2/3) • Solution: use virtual base class inheritance – Only one subobject inherited into multiply derived class Base Class virtual inheritance First Derived Class Second Derived Class Multiply-Derived Class 虛擬繼承是在繼承時寫 : virtual 交通大學資訓 程學系 蔡文能 56

Multiple Inheritance and virtual Base Classes (3/3) class BC { /*. . . */

Multiple Inheritance and virtual Base Classes (3/3) class BC { /*. . . */ }; class FDC : public virtual BC {/*…*/ }; class SDC : virtual public BC {/*…*/ }; class MDC : public FBC, public SDC {/*…*/ }; Example: BC = 人, FDC=老師, SDC =學生, MDC=助教 57 交通大學資訓 程學系 蔡文能

Upcasting and Polymorphism ü Upcasting: Taking an object reference and treating it as a

Upcasting and Polymorphism ü Upcasting: Taking an object reference and treating it as a reference to its base type is called upcasting, because of the way inheritance trees are drawn with the base class at the top. . • 沒有 upcasting 就沒有所謂的Polymorphism(多型) • Base class 的指標(C++)可以指向 derived class 的 object • Base class 的參考(reference, in Java) 可以參考到derived class 的 object • Example: 牛肉麵, 豬肉麵, 羊肉麵 --- 都是麵 (upcasting) 麵 * p = new 牛肉麵( ); ( Java 則不可寫 * ) 58 交通大學資訓 程學系 蔡文能

Polymorphism (多型) in C++ ü Suppose p is a pointer which points to an

Polymorphism (多型) in C++ ü Suppose p is a pointer which points to an object ü class Circle and Line both inherit from Shape. ü All classes have their own draw( ) functions. Shape * p; /* the draw( ) in Shape is virtual or not ? */. p = new Circle( ); P->draw( ); /* which draw( ) will be executed ? */ p = new Line( ); P->draw( ); /* which draw( ) will be executed ? */ ü If draw( ) is virtual, P->draw( ); will run the correct draw( ) 59 交通大學資訓 程學系 蔡文能

Polymorphism, C++ example (1/2) // polymo. cpp -- Copy. Wrong by tsaiwn@csie. nctu. edu.

Polymorphism, C++ example (1/2) // polymo. cpp -- Copy. Wrong by tsaiwn@csie. nctu. edu. tw #include <iostream. h> class Shape{ public: virtual // 把這列去掉再 run 看看, 去掉就沒 polymorphism void draw( ) { cout << "drawingn"; } }; class Line: public Shape{ public: void draw( ) { cout << "draw a linen"; } }; class Circle: public Shape{ public: void draw( ) { cout << "here is a circlen"; } }; 60 交通大學資訓 程學系 蔡文能

Polymorphism, C++ example (2/2) int main( ) { Circle * ppp; Shape * fig[9];

Polymorphism, C++ example (2/2) int main( ) { Circle * ppp; Shape * fig[9]; // base class的指標可指向衍生出的object // ppp = new Shape( ); // error! ppp = (Circle *)new Shape( ); /* cast */ ppp -> draw( ); ppp = (Circle *)new Line( ); ppp -> draw( ); ppp = new Circle( ); ppp -> draw( ); cout << "======" << endl; fig[0] = new Line( ); fig[1] = new Circle( ); fig[2] = new Circle( ); fig[3] = new Line( ); fig[4] = new Circle( ); for(int k=0; k<5; k++){ fig[k] -> draw( ); } } 61 交通大學資訓 程學系 蔡文能

Polymorphism: 用 Base class 的 pointer 操作derived class 的物件 class Shape{ public: virtual void

Polymorphism: 用 Base class 的 pointer 操作derived class 的物件 class Shape{ public: virtual void draw( ) = 0; // pure virtual function }; class Circle: public Shape { // Circle is a Shape void draw( ) { } // must implement this }; Class Line: public Shape { void draw( ) { /*…*/ } }; // Line is a Shape * p; p = new Shape( ); // Wrong ! 因為 Shape 為 ABC p = new Circle( ); // OK, good! P-> draw( ); // will run Circle: : draw( ) P = new Line( ); p-> draw( ); // 用 Line 的 draw( ) 62 交通大學資訓 程學系 蔡文能

Why virtual function? • Virtual function to achieve Polymorphism – Dynamic binding : Shape

Why virtual function? • Virtual function to achieve Polymorphism – Dynamic binding : Shape * p; p-> draw( ); //被譯為執行 p 指過去的object所屬的 class之 draw( ) 函數. 該object有包括一指標會指到正 確的函數 (在 object 被 new 出之時才填入的, 例 p= new Circle( ); 時會填指標指向Circle( ) 的 draw() function ) Polymorphism (多型)! • What if not virtual? – Static binding 較有效率, 但可能錯 : 假設 draw( )不是 virtual Shape * p; p-> draw( ); //一定被譯為 Shape: : draw( ); C++class 的 function 程式人員可決定是否 virtual Java 的 functions 永遠自動 virtual, except final functions 交通大學資訓 程學系 蔡文能 63

ABC (Abstract Base Class) • Abstract Base Class (抽象基底類別) – Base Class ? Derived

ABC (Abstract Base Class) • Abstract Base Class (抽象基底類別) – Base Class ? Derived class ? Super class ? – Abstract Class? • 含有 pure virtual function 的 class • Virtual function? • Pure Virtual function? – virtual void haha( long para) = 0; – Abstract class 不可以用來生出 Object – 專為 polymorphism 而設的class, 提供一致的 interface 65 交通大學資訓 程學系 蔡文能

The Big 3 in C++ • Default Constructor • Copy Constructor • Assignment Operator

The Big 3 in C++ • Default Constructor • Copy Constructor • Assignment Operator • 注意 Operator Overloading 可以寫成: – 自己人 – 朋友 66 交通大學資訓 程學系 蔡文能

////// // constructor/destructor // copy constructor vs. assigment operator=() // member operator/function vs. friend

////// // constructor/destructor // copy constructor vs. assigment operator=() // member operator/function vs. friend operator/function ///////////////////////////// #include <iostream> // #include <iostream. h> using namespace std; // may not necessary for OLD C++ class INT{ long val_; public: INT(){ val_= -999; cout << ": hi. . "; } INT(long n){ val_ = n; cout << ": ha. . "<<val_; } INT(const INT& k){ val_ = k. val_; cout << "(copy "<<val_<<")"; } friend ostream& operator<<(ostream&, const INT&); //friend ostream& operator<<(ostream&, const INT); ~INT(){ cout << " ["<< val_ << " is dying. . . n"; } INT& operator+(const INT&n); //注意"+"和"*"用不同寫法: member vs friend INT friend operator*(const INT&, const INT&); // 注意參數 INT& operator=(const INT&n) //overload assignment function INT: : operator=(INT&n) { this->val_ = 100* n. val_; cout << "(="<<val_<<")"; Default constructor return *this; } }; Assignment Operator myint. cpp(1/3) Copy constructor 交通大學資訓 程學系 蔡文能 67

extern INT x; // 這只是宣告 INT y(5252); // declare + define int main(){ INT

extern INT x; // 這只是宣告 INT y(5252); // declare + define int main(){ INT a, b(38) ; // "hi. . " for a, "ha. . " for b cout << endl << "- - -" << endl; cout << "a=" << a << endl; cout << "b=" << b << endl; INT c(b); // invoke copy construtor to construct c INT d = c; // same as above, this invokes copy construtor too INT e; e=b; // invoke assignment function (operator=) cout << endl << "------" << endl; cout << "c=" << c << endl; cout << "d=" << d << endl; cout << "e=" << endl; cout << "x=" << x << endl; cout << "y=" << y << endl; cout << "== now do x=250; ==n"; x=250; cout << "x=" << x << endl; cout << "== now do c= e + d; == Note 加的結果n"; c = e + d; cout << "c=" << c << endl; cout << "d=" << d << endl; cout << "== now do d= d + 25; == Did we define operator+(INT&, int) ? n"; cout << "== actually, 'cast' will happen. (INT)25 invokes INT(25)n"; d = d + 25; cout << "d=" << d << endl; cout << "== Now output e ==n"; cout << "e=" << endl; myint. cpp(2/3) 交通大學資訓 程學系 蔡文能 68

cout << "== Now output d*e == Note * 的結果n"; cout << "d*e= "

cout << "== Now output d*e == Note * 的結果n"; cout << "d*e= " << d*e <<endl; cout << "x=" << x << endl; cout << "y=" << y << endl; cout << "=== bye 最先生的最慢死 ===n"; cout << "=== y x a b c d e. . . e d c b a x y ===n"; myint. cpp(3/3) } INT x(49); ostream& operator<<(ostream& out, const INT&n) { out << n. val_; return out; } //overload assignment function INT: : operator+(INT&n) INT& INT: : operator+(const INT&n) { val_ = this->val_ - n. val_; /// Note that this "+" has side effect ! //////////////////// cout<<"(addition done: "<<val_<<")"; return *this; } INT operator*(const INT&a, const INT&b) { INT tmp; cout << "(doing *)"; tmp. val_ = a. val_ & b. val_; // bit-wise and cout << "(* done)"; return tmp; } 交通大學資訓 程學系 蔡文能 Default constructor Copy constructor Assignment Operator 69

Run myint. cpp : ha. . 5252: ha. . 49: hi. . : ha.

Run myint. cpp : ha. . 5252: ha. . 49: hi. . : ha. . 38 --== Now output d*e == Note * 的結果 a=-999 : hi. . (doing *)(* done)d*e= 1040 b=38 [1040 is dying. . . (copy 38): hi. . (=3800) x=25000 -----y=5252 c=38 === bye 最先生的最慢死 === d=38 === y x a b c d e. . . e d c b a x y === e=3800 [3762 is dying. . . x=49 [1300 is dying. . . y=5252 [376200 is dying. . . == now do x=250; == [38 is dying. . . : ha. . 250(=25000) [250 is dying. . . [-999 is dying. . . x=25000 [25000 is dying. . . == now do c= e + d; == Note 加的結果 [5252 is dying. . . (addition done: 3762)(=376200)c=376200 d=38 == now do d= d + 25; == Did we define operator+(INT&, int) ? == actually, 'cast' will happen. (INT)25 invokes INT(25) : ha. . 25(addition done: 13)(=1300) [25 is dying. . . d=1300 == Now output e == e=3762 70 交通大學資訓 程學系 蔡文能

如何安全讀入變數值? (6/8) 在 C 程式檔案讀寫 binary file ü fread 與 fwrite FILE * fp;

如何安全讀入變數值? (6/8) 在 C 程式檔案讀寫 binary file ü fread 與 fwrite FILE * fp; /* FILE 為一個 struct */ fp = fopen("filename. ext", "rb"); fread(buf, 1, sizeof(buf), fp); /* buf 為 char array */ fclose(fp); fp = fopen("filename. ext", "wb"); fwrite(buf, 1, sizeof(buf), fp); /* buf 為 char array */ *** 請參看 man fseek, man fscanf 和 man fgetc 及其 see ALSO. . . 76 交通大學資訓 程學系 蔡文能

Writing data to a file (1/2) We can write to a file with an

Writing data to a file (1/2) We can write to a file with an ofstream object: #include <iostream> #include <fstream> #include <cstdlib> using namespace std; int main(){ // create an ofstream object (name arbitrary). . . ofstream my. Output; // Now open a new file. . . my. Output. open("my. Data. File. dat"); // check that operation worked. . . if ( my. Output. fail() ) { cout << "Sorry, couldn’t open file" << endl; exit(1); // from cstdlib } // if. . . Glen Cowan RHUL Physics 交通大學資訓 程學系 蔡文能 Computing and Statistical Data 79 Analysis

Writing data to a file (2/2) Now the ofstream object behaves like cout: for

Writing data to a file (2/2) Now the ofstream object behaves like cout: for (int i=1; i<=n; i++){ my. Output << i << "t" << i*i << endl; } Note use of tab character t formatting (could also use e. g. " " or) Alternatively use the functions setf, precision, width, etc. These work the same way with an ofstream object as they do with cout, e. g. , my. Output. setf(ios: : fixed); my. Output. precision(4); . . . Glen Cowan RHUL Physics 交通大學資訓 程學系 蔡文能 Computing and Statistical Data 80 Analysis

File access modes The previous program would overwrite an existing file. To append an

File access modes The previous program would overwrite an existing file. To append an existing file, we can specify: my. Output. open("my. Data. File. dat", ios: : app); This is an example of a file access mode. Another useful one is: my. Output. open("my. Data. File. dat", ios: : bin); The data is then written as binary, not formatted. This is much more compact, but we can’t check the values with an editor. For more than one option, separate with vertical bar: my. Output. open("my. Data. File. dat", ios: : bin | ios: : app); Many options, also for ifstream. Google for details. Glen Cowan RHUL Physics 交通大學資訓 程學系 蔡文能 Computing and Statistical Data 81 Analysis

C++ I/O Library (1/8) • Input/Output in C++ – Performed with streams of characters

C++ I/O Library (1/8) • Input/Output in C++ – Performed with streams of characters – Streams sent to input/output objects • Input – std: : cin - standard input object (connected to keyboard) – >> stream extraction operator ("get from") ü std: : cin >> my. Variable; Ø Gets stream from keyboard and puts it into my. Variable • Output – std: : cout - standard output stream (connected to screen) – << stream insertion operator ("put to") ü std: : cout << "hi"; Ø Puts "hi" to std: : cout, which prints it on the screen – std: : cerr - standard error report stream (connected to screen) 82 交通大學資訓 程學系 蔡文能

C++ I/O Library (2/8) • std: : endl – "end line" – Stream manipulator

C++ I/O Library (2/8) • std: : endl – "end line" – Stream manipulator - prints a newline and flushes output buffer • Some systems do not display output until "there is enough text to be worthwhile" • std: : endl forces text to be displayed std: : cout << std: : endl; • using namespace statements – Allow us to remove the std: : prefix using namespace std; // 此後不用寫前置的 std: : • Cascading – Can have multiple << or >> operators in a single statement std: : cout << "Hello " << "there" << std: : endl; 83 交通大學資訓 程學系 蔡文能

C++ I/O Library (3/8) • iostream library: – <iostream>: Contains cin, cout, cerr, and

C++ I/O Library (3/8) • iostream library: – <iostream>: Contains cin, cout, cerr, and clog objects – <iomanip>: Contains parameterized stream manipulators – <fstream>: Contains information important to user-controlled file processing operations 84 交通大學資訓 程學系 蔡文能

C++ I/O Library (4/8) • cin. get(): inputs a character from stream (even white

C++ I/O Library (4/8) • cin. get(): inputs a character from stream (even white spaces) and returns it • cin. get( c ): inputs a character from stream and stores it in c • cin. get(array, size): – Accepts 3 arguments: array of characters, the size limit, and a delimiter ( default of ‘n’). – Uses the array as a buffer – When the delimiter is encountered, it remains in the input stream – Null character is inserted in the array – Unless delimiter flushed from stream, it will stay there • cin. getline(array, size) – Operates like cin. get(buffer, size) but it discards the delimiter from the stream and does not store it in array – Null character inserted into array 85 交通大學資訓 程學系 蔡文能

C++ I/O Library (5/8) • ignore member function – Skips over a designated number

C++ I/O Library (5/8) • ignore member function – Skips over a designated number of characters (default of one) – Terminates upon encountering a designated delimiter (default is EOF, skips to the end of the file) • putback member function – Places the previous character obtained by get back in to the stream. • peek – Returns the next character from the stream without removing it • read and write member functions – Unformatted I/O – Input/output raw bytes to or from a character array in memory – Since the data is unformatted, the functions will not terminate at a newline character for example • Instead, like getline, they continue to process a designated number of characters – If fewer than the designated number of characters are read, then the failbit is set • Stream manipulators: oct, hex, dec, setbase( ), setprecision( ), setw( ) 86 交通大學資訓 程學系 蔡文能

C++ I/O Library (6/8) • ifstream – Suppose we need an input stream fin

C++ I/O Library (6/8) • ifstream – Suppose we need an input stream fin for extracting values from the file scores. dat – first include the <fstream> library. – The desired stream can be created by defining an ifstream object fin as follows: ifstream fin(“scores. dat”); – The supplied parameter must be a null terminated string, showing the library’s old c routes. However strings have a method called. c_str() that will convert them to this format. – The following statement extracts information from scores. dat: fin >> value; – ifstream is derived from istream we can use the >> operator for ifstream objects. 87 交通大學資訓 程學系 蔡文能

C++ I/O Library (7/8) • ofstream – If we define an ofstream object we

C++ I/O Library (7/8) • ofstream – If we define an ofstream object we can use it to capture insertions to a file. ofstream fout(“results. txt”); fout << value; – The above code simply associates the ofstream object fout with the file results. txt, and then inserts a value into that file. – By default the file associated with ofstream object will be made empty during initialisation. 88 交通大學資訓 程學系 蔡文能

C++ I/O Library (8/8) • open( ) and close( ) member function – Objects

C++ I/O Library (8/8) • open( ) and close( ) member function – Objects of type ifstream and ofstream have several member functions. – close() and open()are two of these. – close() indicates that the processing of the associated file is complete. – conceptually open() has two versions, both requiring a character string, but one version also allows a parameter to specify the mode. (see next slides for various open modes) 89 交通大學資訓 程學系 蔡文能

ios flags for open Mode ofstream fgg; fgg. open("haha. log", ios: : app); ios:

ios flags for open Mode ofstream fgg; fgg. open("haha. log", ios: : app); ios: : app ios: : ate ios: : in ios: : out causes all output to that file to be appended to the end. This value can only be used with files capable of output. causes an initial seek to end of file. specifies that the file is capable of input. specifies that the file is capable of output. ios: : trunc causes the contents of the file to be destroyed , and file size truncated to zero length. ios: : binary this value causes the file to opened in binary mode, as opposed to the default text mode. In binary mode no character translation can occur. 90 交通大學資訓 程學系 蔡文能

<iomanip> functions setw(int w) setfill(int c) left right setbase(int b) fixed scientific showpoint setprecision(int

<iomanip> functions setw(int w) setfill(int c) left right setbase(int b) fixed scientific showpoint setprecision(int d) skipws showpos boolalpha Set field width to w Set the fill character to c Fill characters are padded after the display Fill characters are padded before Set the numeric base to b Display floating-point values in decimal notation Display floating-point values in scientific notation Values are always shown with a decimal point Set number of places accuracy to d Whitespace ignored during extractions Positive numbers have a leading + sign Display logical values symbolically as true/false http: //www. csie. nctu. edu. tw/~tsaiwn/oop/ 交通大學資訓 程學系 蔡文能 91

http: //www. csie. nctu. edu. tw/~tsaiwn/cpp/ 02_ooa_ood. ppt Thank You! 謝謝捧場; 下次見 ! tsaiwn@csie.

http: //www. csie. nctu. edu. tw/~tsaiwn/cpp/ 02_ooa_ood. ppt Thank You! 謝謝捧場; 下次見 ! tsaiwn@csie. nctu. edu. tw 蔡文能 交通大學資訓 程學系 蔡文能 92