890 likes | 908 Views
http://www.csie.nctu.edu.tw/~tsaiwn/oop /. Review: C++ 物件導向程式設計 Introduction to C++ with OOP. 2/3. 蔡文能 tsaiwn@csie.nctu.edu.tw tsaiwn@cs.nctu.edu.tw 交通大學資訊工程學系. 2007/07/17. Agenda. From C to C++ (C++ == a better C + Objec-Oriented support)
E N D
http://www.csie.nctu.edu.tw/~tsaiwn/oop/ Review: C++物件導向程式設計Introduction to C++ with OOP 2/3 蔡文能 tsaiwn@csie.nctu.edu.tw tsaiwn@cs.nctu.edu.tw 交通大學資訊工程學系 2007/07/17 交通大學資訓工程學系 蔡文能
Agenda • From C to C++ (C++ == a better C + Objec-Oriented support) a. I/O stream, b. pass-by-reference c. function name overloading, d.operator overloading, e. default parameter, f.inline function, g.template function • Data Abstraction: Why using struct? Why using class? • An ADT example: How to design/construct/use a Stack? • Introduction to OOA, OOD, and UML • Inheritance and examples: Animal and Mankind, Vector and Stack • virtual function and Polymorphism: How it works? • 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 and access control of class members 交通大學資訓工程學系 蔡文能
Object Oriented Concept OOD, OOP OOA, Review OO Analysis OO Design 交通大學資訓工程學系 蔡文能
OO features • The concept of abstraction is fundamental in programming • Subprogram / function • processabstraction • ADT • Dataabstraction • Encapsulation • Information Hiding 抽象化的概念以前就有: 函數/副程式 增加: • Inheritance • Polymorphism Software Reuse 交通大學資訓工程學系 蔡文能
Class vs. Object • Object is an instance of some class • int x; float yy; • Object(物件, 個體, 東西) -- 就是以前所謂的變數 #include<iostream> struct Student{ long sid; char name[9]; }; Student x, y[99], tempstu; int main( ) { x.sid = 38; // OK! cout << x.sid; // OK! } #include<iostream> class Student{ long sid; char name[9]; }; Student x, y[99], tempstu; int main( ) { x.sid = 38; //Error! cout << x.sid; //Error! } 交通大學資訓工程學系 蔡文能
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? 交通大學資訓工程學系 蔡文能
Struct vs. Class (2/3) #include <iostream.h> class Student { long sid; // default is private for class friend int main( ); }; // 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 ! 交通大學資訓工程學系 蔡文能
Struct vs. Class (3/3) 正確概念是透過 member functions #include <iostream.h> class Student { // private: long sid; public: showNumber( ) { return sid; } setId( long xx) { sid = xx; } }; int main( ) { Student x, y; x.setId(123); // OK, 透過 public function setId( ) cout << "==" << x.showNumber( ) << endl; // OK return 0; } 交通大學資訓工程學系 蔡文能
O O Features • Encapsulation • Information Hiding (Data Hiding) • Inheritance • Polymorphism Object Based For Software Reuse Object Oriented ( 物件導向 ) ( 個體導向 ) 交通大學資訓工程學系 蔡文能
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, … 交通大學資訓工程學系 蔡文能
OOA: CRC Cards • Step two: Write CRC cards and work through scenarios • Class-Responsibility-Collaborator Cards (Cunningham and Beck) • Just 3x5 cards • Although CRC is not part of UML, they add some very useful insights throughout a development. Data fields (attributes) 寫在背面 交通大學資訓工程學系 蔡文能
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 交通大學資訓工程學系 蔡文能
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 交通大學資訓工程學系 蔡文能
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 交通大學資訓工程學系 蔡文能
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 交通大學資訓工程學系 蔡文能
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 UML is a “blueprint” for building complex software 交通大學資訓工程學系 蔡文能
Approved2004 UML 2.0 Minor revision 2003 UML 1.5 Minor revision 1999 OMG Acceptance, Nov 1997 Final submission to OMG, Sept 1997 First submission to OMG, Jan 1997 UML 1.3 UML 1.1 Public Feedback Minorrevision2001 UML 1.0 UML 1.4 UML partners UML 0.9 Web - June 1996 Unified Method 0.8 OOPSLA 95 Booch method OMT Other methods OOSE History of the UML( http://www.uml.org/ ) 交通大學資訓工程學系 蔡文能
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 (有限狀態機). 交通大學資訓工程學系 蔡文能
UML 12 Diagrams • Structural: • Class • Component • Deployment • Object • Behavior : • Use Case • Sequence • Collaboration • State Chart • Activity • Model Management: • Packages (class diagram contains packages) • Subsystems (class diagram contains subsystems) • Models (class diagram contains models) 交通大學資訓工程學系 蔡文能
UML Core Conventions 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.). • Rectangles are classes or instances • Ovals are functions or use cases • Types are denoted with non-underlined names • SimpleWatch • Firefighter • Instances are denoted with an underlined names • myWatch:SimpleWatch • Joe:Firefighter • Diagrams are higraphs • 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) 交通大學資訓工程學系 蔡文能
Package Actor Use case Use Case Diagram examples • 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. SimpleWatch ReadTime SetTime WatchUser WatchRepairPerson ChangeBattery Use case diagrams represent the functionality of the system from user’s point of view. (強調 what, 但暫不管 how) 交通大學資訓工程學系 蔡文能
Class Multiplicity Association Attributes Operations Class Diagram : a simple Watch SimpleWatch 1 1 1 1 1 2 1 2 PushButton state push()release() LCDDisplay Battery load() Time now() blinkIdx blinkSeconds() blinkMinutes() blinkHours() stopBlinking() referesh() Class diagrams represent the structure of the domain or system 交通大學資訓工程學系 蔡文能
Object :SimpleWatch :LCDDisplay :Time :WatchUser pressButton1() blinkHours() pressButton1() blinkMinutes() pressButton2() incrementMinutes() refresh() Sequence diagrams represent the behavior as interactions It shows sequence of events for a particular use case Activation pressButtons1And2() commitNewTime() stopBlinking() Message Activation Sequence Diagram Object diagram with numbered messages Sequence numbers of messages are nested by procedure call Collaboration Diagram 交通大學資訓工程學系 蔡文能
State Initial state Event button2Pressed button1&2Pressed Increment Blink Hours Hours Transition button1Pressed button2Pressed button1&2Pressed Blink Increment Minutes Minutes button1Pressed button2Pressed Blink Stop Increment Seconds Blinking Seconds Final state State chart Diagrams for the watch button1&2Pressed FSM: Finite State Machine 交通大學資訓工程學系 蔡文能
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的操作流程; 像流程圖 交通大學資訓工程學系 蔡文能
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 交通大學資訓工程學系 蔡文能
Visibility shown as + public - private # protected UML Class Class name Data members (attributes) Instance methods Class method (static) Return types Arguments Data members, arguments and methods are specified by visibilityname:type 交通大學資訓工程學系 蔡文能
Class name visibility name : type Class Attributes Attributes are the instance data members and class data members Class data members(underlined) are shared between all instances (objects) of a given class Data types shown after ":" Visibility shown as + public - private # protected Attribute compartment 交通大學資訓工程學系 蔡文能
Operations compartment 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) 交通大學資訓工程學系 蔡文能
Template Classes Type parameter(s) Operations compartment as usual, but may have type parameter instead of concrete type Generic classes depending on parametrised types 交通大學資訓工程學系 蔡文能
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 交通大學資訓工程學系 蔡文能
Multiple Inheritance (Java) The derived class inherits interface, behaviour and data members of all its base classes Extension and overriding works as before implements extends B implements the interface A and is also a "countable" class since it inherits class Countable class B extends Countable implements A { /*…*/ } 交通大學資訓工程學系 蔡文能
A is associated with B • A has a B • A has a method that returns a B • vice versa • etc. 交通大學資訓工程學系 蔡文能
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! 交通大學資訓工程學系 蔡文能
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 交通大學資訓工程學系 蔡文能
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/CoWeb • Argo-UML, ObjectPlant, Posiden, etc. 交通大學資訓工程學系 蔡文能
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 交通大學資訓工程學系 蔡文能
Other O-O Languages (2/2) • C# (唸作 C-Sharp, by MicroSoft) • 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 交通大學資訓工程學系 蔡文能
Inheritance (繼承, 擴充) (1/3) class Animal{ long height; protected: double hehe; public: float weight; void jump( ) { /** … **/ } }; int main( ) { Animal x; Mankind y; x.jump( ); cout << sizeof(x)<<endl; cout << sizeof(y)<<endl; y.jump( ); y.talk( ); } class Mankind : public Animal { long iq; public: void jump( ) { /** override **/ } void talk( ) { /** new **/ } }; In C++, ";" is required to terminate a class 交通大學資訓工程學系 蔡文能
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 className: memberAccessSpecifier baseClassName { // member list … } • memberAccessSpecifier can be public, protected and private • If nomemberAccessSpecifier, it is a private inheritance 交通大學資訓工程學系 蔡文能
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 memberAccessSpecifieris public, all the members of the base class keep their access rights in the derived class • If memberAccessSpecifieris protected, the public members of the base class become protected in the derived class, but the protected and private keep no change • If memberAccessSpecifieris private, all the members of the base class become private in the derived class 若沒有繼承, 則寫 protected 與 private 完全相同 交通大學資訓工程學系 蔡文能
How can two classes be related?Inherits, Contains, TalksTo • Generalization-specialization or IsA • NamedBox IsA Box • Diagram: Triangle on the relationship line (參考前面 UML ) • Association or HasA • Box HasA Pen • Diagram: Just a relationship line (參考前面 UML ) • Aggregation is a part-whole relationship • Diagram: Diamond on the line (參考前面 UML ) • Dependency or TalksTo • Dependency is sort of temporary HasA • Diagram: Dashed line in UML (參考前面 UML ) 交通大學資訓工程學系 蔡文能
public 繼承 Mankindinherits Animal (C++) class Animal { int height = 0; int weight = 0; public: void talk( ) { printf("Won");} }; classMankind:publicAnimal { private: int iq = 120; public: void talk( ) { printf("Hello");} }; /* 分號不能省掉 */ Classes can be in same file In C++, ";" is required to terminate a class 交通大學資訓工程學系 蔡文能
Take a Break 10 minutes 不 要 走 開 ! tsaiwn@cs.nctu.edu.tw 蔡文能 交通大學資訓工程學系 蔡文能
manlib.h #ifndef __MANLIB__ #define __MANLIB__ class animal { // 建議大寫開頭: class Animal { int pv1; float pv2; protected: int pt1[5]; public: animal(int = 38); // default parameter float pb1; int pb2[9]; void talk(void); }; class Mankind:public animal { char * pv3; public: Mankind(char * ="NoName"); // Constructor with default 參數 ~Mankind( ); // Destructor int pb3[8]; void talk(void); }; #endif 交通大學資訓工程學系 蔡文能
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 pv1=x; pv2=45.67; this->pb1=135.246; for (int i=0; i<9; i++) pb2[i]=i+1; //pb2={ 1,2,3,4,5,6,7 ,8,9}; cout<<" Animal shows up\n"; }; void animal::talk(void) { cout << " animal talk, pv1=" << dec <<pv1 <<"=0x" << hex << pv1 <<"\n"; cout << " \t pv2=" << pv2 <<"\n"; cout << " \t pb1=" << pb1 <<"\n"; cout << " \t pb2[6]=" << pb2[6] <<"\n"; }; 交通大學資訓工程學系 蔡文能
manlib.cpp (2/2) Mankind::Mankind(char * name){ pv3=name; cout << " Mankind "<< pv3 << " appears\n"; } Mankind::~Mankind(void){ cout << " %%% Mankind "<< this->pv3 << " is dying \n";} void Mankind::talk(void) { // cout << " Mankind talk, pv1=" << pv1 <<"\n"; // cout << " Mankind talk, pb2=" << pb2 <<"\n"; // cout << " Mankind talk, pb2=" << animal::pb2 <<"\n"; cout << " Mankind talk, pb2[0]=" << pb2[0] <<"\n"; cout << " Mankind talk, pv3=" << pv3 <<"\n"; cout << " Mankind talk, pb3[3]=" << pb3[3] <<"\n"; }; 交通大學資訓工程學系 蔡文能
Using Mankind 與 animal (mannew.cpp) main( ) { aa1.talk(); cout << "Welcome to C++\n"; call onlyasub(); mm1= new Mankind("Chang-3"); mm2= new Mankind("Lee-4"); cout << "mm1->pb1= " << mm1->pb1 << endl; cout << " (Let mm1 talk)\n"; mm1->talk( ); delete mm2; cout << " (and then Let mm1 talk" << " by animal method)\n"; mm1->animal::talk( ); return(0); } #include <stdio.h> #include <iostream> // 注意 // #include <iostream.h> #define call #include "manlib.h" // 舊的C++不能用 Using namespace std; animal aa1(123), aa2(456); Mankind * mm1, *mm2; void onlyasub(void) { Mankind nobody; cout << " Now in routine onlyasub\n"; } 交通大學資訓工程學系 蔡文能
Using Mankind 與 animal (mannew.cpp) #include <stdio.h> #include <iostream> // #include <iostream.h> #define call #include "manlib.h" Using namespace std; animal aa1(123), aa2(456); Mankind * mm1, *mm2; void onlyasub(void) { Mankind nobody; cout << " Now in routine onlyasub\n"; } main(){ aa1.talk(); cout << "Welcome to C++\n"; call onlyasub(); mm1= new Mankind("Chang-3"); mm2= new Mankind("Lee-4"); cout << "mm1->pb1=" << mm1->pb1 << "\n"; cout << " (Let mm1 talk)\n"; mm1->talk( ); delete mm2; cout << " (and then Let mm1 talk by animal method)\n"; mm1->animal::talk( ); return(0); } 交通大學資訓工程學系 蔡文能
Test class Mankind and animal 注意比對 running result 與 程式碼! g++ -c manlib.cpp g++ mannew.cpp manlib.o ./a.out Animal shows up Animal shows up animal talk, pv1=123=0x7b pv2=45.67 pb1=135.246 pb2[6]=7 Welcome to C++ Animal shows up Mankind NoName appears Now in routine onlyasub %%% Mankind NoName is dying Animal shows up Mankind Chang-3 appears Animal shows up Mankind Lee-4 appears mm1->pb1=135.246 (Let mm1 talk) Mankind talk, pb2[0]=1 Mankind talk, pv3=Chang-3 Mankind talk, pb3[3]=0 %%% Mankind Lee-4 is dying (and then Let mm1 talk by animal method) animal talk, pv1=38=0x26 pv2=45.67 pb1=135.246 pb2[6]=7 交通大學資訓工程學系 蔡文能