C++ 物件導向程式設計 Introduction to C++ with OOP

92
交交交交交交交交交交 交交交 1 C++ 交交交交交交交交 Introduction to C++ wi th OOP 交交交 [email protected] [email protected] 交交交交交交交交交交 2007/07/24 http://www.csie.nctu.edu.tw/ ~tsaiwn/cpp/ 02_ooa_ood. ppt

description

http://www.csie.nctu.edu.tw/~tsaiwn/cpp /. 02_ooa_ood.ppt. C++ 物件導向程式設計 Introduction to C++ with OOP. 蔡文能 [email protected] [email protected] 交通大學資訊工程學系. 2007/07/24. Agenda. Review : How to design/construct/use a Stack? Introduction to OOA, OOD, and UML - PowerPoint PPT Presentation

Transcript of C++ 物件導向程式設計 Introduction to C++ with OOP

Page 1: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

1

C++ 物件導向程式設計Introduction to C++ with OOP

蔡文能[email protected]@cs.nctu.edu.tw

交通大學資訊工程學系2007/07/24

http://www.csie.nctu.edu.tw/~tsaiwn/cpp/

02_ooa_ood.ppt

Page 2: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

2

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 and access control of class members

Page 3: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

3

Object Oriented Concept

Review

OO Analysis

OO Design

OOA, OOD, OOP

Page 4: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

4

OO featuresEncapsulationInformation Hiding The concept of abstraction is

fundamental in programming

Subprogram / function

process abstraction

ADT

Data abstractionSoftware Reuse

增加 :InheritancePolymorphism

抽象化的概念以前就有 : 函數 / 副程式

Page 5: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

5

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 x, y[99], chang3;

這些是 Object

Student 是 class ( 類別 )

Page 6: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

6

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>struct Student{ // public:

long sid;

char name[9];

};

Student x, y[99], tempstu;

int main( ) { x.sid = 38; // OK! cout << x.sid; // OK!}

Default is private: Default is public:

Page 7: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

7

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?

Page 8: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

8

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 !

可以稱朋友 : 耍特權

Page 9: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

9

Struct vs. Class (3/3) #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;

}

正確概念是透過 member functions

Page 10: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

10

O O Features

• Encapsulation• Information Hiding (Data Hiding)

• Inheritance• Polymorphism

Object Based

Object Oriented ( 物件導向 ) ( 個體導向 )

For Software Reuse

Page 11: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

11

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, …

Page 12: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

12

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

– Class-Responsibility-Collaborator Cards (Cunningham and Beck)– Just 3x5 cards

Data fields (attributes) 寫在背面

•Although CRC is not part of UML, they add some very useful insights throughout a development.

Page 13: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

13

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

Page 14: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

14

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

Page 15: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

15

MDA-Model Driven Architecture?

• A New Way to Specify and Build Systems– 2001 年由 OMG 制定的新開發架構 (http://www.omg.o

rg)

– 以 UML Model( 塑模 ) 為基礎– 支援完整開發週期 : Analysis, Design, Implementation,

Deployment, Maintenance, Evolution & Integration with later systems ( 改進與後續整合 )

– 內建協同運作性及跨平台性– 降低開發初期成本及提高 ROI ( 投資報酬 )

– 可套用至你所使用的任何環境 :

• Programming language Network

• Operating System Middleware

Page 16: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

16

Unified Modeling Language

• 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)

http://www.UML.org

amigos = friends

http://www.omg.org

(Object Constrain Language)

Page 17: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

17

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 m

odels organized around the real world ideas.• Resulted from the convergence of notations from three lea

ding 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

軟體工程師共通的語言

Page 18: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

18

History of the UML( http://www.uml.org/ )

PublicFeedback

Web - June 1996 Web - June 1996 UML 0.9UML 0.9

Unified Method 0.8Unified Method 0.8OOPSLA 95OOPSLA 95

UML 1.0UML 1.0UML partnersUML partners

OMG Acceptance, Nov 1997Final submission to OMG, Sept 1997First submission to OMG, Jan 1997

OMG Acceptance, Nov 1997Final submission to OMG, Sept 1997First submission to OMG, Jan 1997

UML 1.1UML 1.1

UML 2.0UML 2.0Approved 2004Approved 2004

Minor revision 1999 Minor revision 1999 UML 1.3UML 1.3

UML 1.4UML 1.4Minor revision 2001Minor revision 2001

OOSEOther methods OMTBooch method

Minor revision 2003Minor revision 2003 UML 1.5UML 1.5

Page 19: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

19

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 ( 有限狀態機 ).

Page 20: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

20

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)

Page 21: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

21

UML Core Conventions• 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)

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.).

Page 22: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

22

Use Case Diagram examples

WatchUserWatchRepairPerson

ReadTime

SetTime

ChangeBattery

Actor

Use case

PackageSimpleWatch

Use case diagrams represent the functionality of the systemfrom user’s point of view. ( 強調 what, 但暫不管 how)

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.

Page 23: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

23

Class Diagram : a simple Watch

Batteryload()

1

2

Timenow()

PushButtonstatepush()release()

1

1

1

1

1

2

blinkIdxblinkSeconds()blinkMinutes()blinkHours()stopBlinking()referesh()

LCDDisplay

SimpleWatch

Class

Association

Operations

Class diagrams represent the structure of the domain or system

Attributes

Multiplicity

Page 24: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

24

Sequence DiagramObject

MessageActivation

Sequence diagrams represent the behavior as interactionsIt shows sequence of events for a particular use case

blinkHours()blinkMinutes()

incrementMinutes()refresh()

commitNewTime()stopBlinking()

pressButton1()

pressButton2()

pressButtons1And2()

pressButton1()

:WatchUser :Time:LCDDisplay:SimpleWatch

Activation

Collaboration Diagram

Object diagram withnumbered messages

Sequence numbers of messages are nested by procedure call

Page 25: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

25

button1&2Pressed

button1&2Pressed

button1Pressed

button2Pressed

button2Pressed

button2Pressed

button1Pressed

button1&2Pressed IncrementMinutes

IncrementHours

BlinkHours

BlinkSeconds

BlinkMinutes

IncrementSeconds

StopBlinking

State chart Diagrams for the watchStateInitial state

Final state

Transition

Event

FSM: Finite State Machine

Page 26: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

26

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 的操作流程 ; 像流程圖

HandleIncident

DocumentIncident

ArchiveIncident

Page 27: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

27

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

Page 28: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

28

UML ClassClass name

Data members(attributes)

Instance methods

ArgumentsReturn typesClass method (static)

Data members, arguments and methods are specified byvisibility name : type

Visibility shown as+ public- private# protected

Page 29: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

29

Class AttributesAttributes are the instance data membersand 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

Attributecompartment

visibility name : type

Class name

Page 30: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

30

Class Operations (Interface)

Operations are the classmethods with their argumentand return types

Public (+) operations define theclass interface

Class methods (underlined) can only access to class datamembers, no need for a classinstance (object)

Operationscompartment

Page 31: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

31

Template Classes

Generic classes depending on parametrised types

Type parameter(s)

Operations compartmentas usual, but may havetype parameter instead ofconcrete type

Page 32: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

32

Class InheritanceBase class or super class

Derived class or subclass

Arrow shows directionof dependency (B inherits A)

→ B inherits A's interface, behaviour and data members

→ B can extend A, i.e. add newdata members or member functions

→ B depends on A,A knows nothing about B

Page 33: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

33

Multiple Inheritance (Java)

The derived class inheritsinterface, behaviour anddata members of all itsbase classes

Extension and overridingworks as before

B implements the interface A andis also a "countable" class since itinherits class Countable

extends

implements

class B extends Countable implements A { /*…*/ }

Page 34: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

34

A is associated with B

• A has a B

• A has a method that returns a B

• vice versa

• etc.

Page 35: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

35

Class FriendshipFriends are granted access to private data members andmember functionsFriendship is given to other classes, never taken

Friendship breaks data hiding, use carefully !

Friend is the only one who can touch your private!

Page 36: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

36

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

Page 37: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

37

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.

Page 38: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

38

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

Page 39: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

39

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 rar

ely used– structs are lightweight classes that do not support inheritance– Common solution to need for access to data members: accessor metho

ds (getter and setter)– C# provides properties as a way of implementing getters and setters w

ithout requiring explicit method calls

Page 40: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

40

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

Page 41: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

41

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:

memberAccessSpecifier can be public, protected and private

If no memberAccessSpecifier, it is a private inheritance

Class className: memberAccessSpecifier baseClassName

{

// member list …

}

Page 42: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

42

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 memberAccessSpecifier is public, all the members of the base class keep their access rights in the derived class

If memberAccessSpecifier is protected, the public members of the base class become protected in the derived class, but the protected and private keep no change

If memberAccessSpecifier is private, all the members of the base class become private in the derived class

若沒有繼承 , 則寫 protected 與 private 完全相同

Page 43: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

43

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 )

Page 44: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

44

Mankind inherits Animalclass Animal { int height = 0; int weight = 0; public: void talk( ) { printf("Won");}};

class Mankind :public Animal { private: int iq = 120; public: void talk( ) { printf("Hello");}}; /* 分號不能省掉 */

Classes can be in same file

In C++, ";" is required to terminate a class

public 繼承

(C++)

Page 45: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

45

Mankind extends Animalpublic 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

Should be in different files

One Java file can only have one public class

不要管文法

(Java)

Page 46: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

46

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

Page 47: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

47

manlib.cpp (1/2)// Implementation file for "animal" and "Mankind"#include <stdio.h>#include <iostream> //#include <iostream.h> // 舊的 C++ 用 iostream.husing 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";};

Page 48: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

48

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";};

Page 49: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

49

Using Mankind 與 animal (mannew.cpp)

#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";}

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);}

Page 50: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

50

Using Mankind 與 animal (mannew.cpp)#include <stdio.h>

#include <iostream> // 舊版 C++ 用 #include <iostream.h>#define call#include "manlib.h"using namespace std; // 舊版 C++ 不認識這 namespace statementanimal 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);}

Page 51: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

51

Test class Mankind and animalg++ -c manlib.cppg++ 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]=7Welcome 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 appearsmm1->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

注意比對 running result 與 程式碼 !

Page 52: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

52

問題與思考 : inherit == extend

class 豪華鬧鐘 : public 鬧鐘 {

// … 豪華鬧鐘 is_a 鬧鐘};

class Stack : private Deque {

// …

};

class Stack {

Deque x; // …

};

class Stack : public Vector {

// …

};

class Stack {

Vector x; // …

};

Page 53: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

53

Take a BreakTake a Break

不 要 走 開 [email protected]

蔡文能

12 minutes

http://www.csie.nctu.edu.tw/~tsaiwn/cpp/

Page 54: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

54

Multiple Inheritance ?

Person

NurseDoctor

Surgeon FamilyDoctor

單一繼承

Vehicle

Land Vehicle Water Vehicle

Car Amphibious Vehicle Boat

多重繼承

Another Problem? 源自 vehicle 的資料會有兩份

Solution? 用 virtual 繼承

Multiple inheritance is powerful, but can cause ambiguity problemsIf both base classes have functions of the same nameSolution: specify exact function/data using ::

myObject.BaseClass1::function( )

Java 不可多重繼承 ; 但可多重 implements

Page 55: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

55

Multiple Inheritance and virtual Base Classes (1/3)

• Ambiguities from multiple inheritance

• 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

ios

ostreamistream

iostream

Page 56: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

56

Multiple Inheritance and virtual Base Classes (2/3)

• Solution: use virtual base class inheritance– Only one subobject inherited into multiply derived clas

s

Second Derived Class

Base Class

First Derived Class

Multiply-Derived Class

virtual inheritance

virtual inheritance

虛擬繼承是在繼承時寫 :virtual

Page 57: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

57

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= 助教

Page 58: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

58

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 則不可寫 * )

.

Page 59: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

59

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( )

.

Page 60: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

60

Polymorphism, C++ example (1/2)// polymo.cpp -- CopyWrong by [email protected]#include <iostream.h>class Shape{ public: virtual // 把這列去掉再 run 看看 , 去掉就沒 polymorphism void draw( ) { cout << "drawing\n"; }};class Line: public Shape{ public: void draw( ) { cout << "draw a line\n"; }};class Circle: public Shape{ public: void draw( ) { cout << "here is a circle\n"; }};

Page 61: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

61

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( ); }}

Page 62: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

62

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 Shape * p;p = new Shape( ); // Wrong ! 因為 Shape 為 ABCp = new Circle( ); // OK, good!P-> draw( ); // will run Circle::draw( )P = new Line( ); p-> draw( ); // 用 Line 的 draw( )

Page 63: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

63

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 )

• What if not virtual?– Static binding 較有效率 , 但可能錯 : 假設 draw( ) 不是 virt

ual

Shape * p;

p-> draw( ); // 一定被譯為 Shape::draw( );C++class 的 function 程式人員可決定是否 virtual

Polymorphism ( 多型 )!

Java 的 functions 永遠自動 virtual, except final functions

Page 64: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

64

C++ How to …overloading/polymorphism C++ 到底是用了什麼技術辦到 function name overloading ? 事實上

只是用了一個超級簡單的 idea:– C++ 只是把參數的型別納入函數名稱中而已 , Compiler 會偷換 f

unction name, 參數的 type 也變成 function_name 的一部份 : ( static binding)

例如 : void swap(int&, int&); 會被譯為 ( 可能 !): __swap_F2RiRi

如何達成 polymorphism ? (C++ 要用到指標才有多型 ) 透過 virtual function dynamic binding p-> draw( ); 譯成去執行 p 指過去之物件內有個指標指過

去的函數表中 draw 的項目位置指過去的那個函數 ! ( 相關指標在 new 出物件時填入 )

若 draw( ) 不是 virtual, 則 p-> draw( ); 會採用 static binding 方式翻譯 , 即依據宣告看 p 是啥的指標直接譯出要執行哪個 function

Page 65: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

65

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

Page 66: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

66

The Big 3 in C++

• Default Constructor

• Copy Constructor

• Assignment Operator

• 注意 Operator Overloading 可以寫成 :– 自己人– 朋友

Page 67: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

67

myint.cpp(1/3)//////// 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_<<")"; return *this; }};

Default constructorCopy constructor

Assignment Operator

Page 68: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

68

myint.cpp(2/3)extern INT x; // 這只是宣告INT y(5252); // declare + defineint 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=" << 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=" << e << endl;

Page 69: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

69

myint.cpp(3/3)cout << "== Now output d*e == Note * 的結果 \n"; cout << "d*e= " << d*e <<endl; cout << "x=" << x << endl; cout << "y=" << y << endl; cout << "=== bye bye 最先生的最慢死 ===\n"; cout << "=== y x a b c d e ... e d c b a x y ===\n";}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 constructorCopy constructor

Assignment Operator

Page 70: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

70

Run myint.cpp:ha..5252:ha..49:hi..:ha..38- - -a=-999b=38(copy 38)(copy 38):hi..(=3800)------c=38d=38e=3800x=49y=5252== now do x=250; ==:ha..250(=25000) [250 is dying...x=25000== now do c= e + d; == Note 加的結果(addition done:3762)(=376200)c=376200d=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

== Now output d*e == Note * 的結果:hi..(doing *)(* done)d*e= 1040 [1040 is dying...x=25000y=5252=== bye bye 最先生的最慢死 ====== y x a b c d e ... e d c b a x y === [3762 is dying... [1300 is dying... [376200 is dying... [38 is dying... [-999 is dying... [25000 is dying... [5252 is dying...

Page 71: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

71

如何安全讀入變數值 ? (1/8)• 常見用法 , 但是危險 ! 容易被 user 輸入弄當掉 (why? ) (1) 用到輸出 /輸入應該要 #include <stdio.h> (2) 輸出實數 : printf("%f", number);

其中的 number 可為 float 也可為 double 這是因為 C 傳參數時 float 都會被轉為 double 傳過去 (3)輸出整數 : printf("%d", number);

此處的 number 為 int; 若是 long 則用 %ld; 若是 short 用 %hd (4) 輸入實數 : scanf("%f %lf", &numfloat, &numdouble); 此處的 numfloat 為 float; numdouble 為 double; (5) 若要輸入整數時讀入 long 要用 "%ld", int 用 "%d", short 用 "%

hd" (6) 注意輸入實數的 scanf 與輸出實數的 printf 所用格式 ! printf 時 float 和 double 都用 %f 可是 scanf 或 sscanf 時讀入 double 要用 "%lf", float 用 "%f"

Page 72: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

72

如何安全讀入變數值 ? (2/8)

希望不會被 user 輸入弄當掉 , 則 :輸入時儘量先用 fgets 讀入 buffer 再做處理 , 不

要直接用 scanf ( 注意 : gets( ) 也很危險 ! See next slide)

static char buf[999]; int age; fprintf(stderr, "請輸入年齡 : "); fgets(buf, sizeof(buf), stdin); /* 儘量不要偷 懶用 gets(buf);

*/

sscanf(buf, "%d", &age); /* 從 buf 中 scan */ 若只有一個數也可以用 age = atol(buf); /* 整數 */

或是 age = atof(buf); /* double or float 實數 */

Page 73: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

73

如何安全讀入變數值 ? (3/8)

• 萬惡之首 gets

static char buf[99];

gets(buf);

/* 若輸入超過 99 char 會怎樣 ? */

/* 會死得不明不白 */

會被駭客利用 !

Page 74: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

74

如何安全讀入變數值 ? (4/8)

檔案讀寫 (File I/O) OS_level: 0 號 , 1號 , 2號 三個檔案 C語言的看法 : stdin, stdout, stderr C++ 語言的看法 : cin, cout, cerr Java 語言的看法 :

System.in, System.out, System.err System.class 是一個 static class 該 class 內有三個物件 : in, out, err

Page 75: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

75

如何安全讀入變數值 ? (5/8)

在 C 程式檔案讀寫 (File I/O) FILE * fp;

fp = fopen("filename.ext", "rt"); /* 文字檔輸入用 "rt", 輸出用 "wt" */

if(fp==0) /* 則表示 open 沒有成功 ... */

– fgets(buf, sizeof(buf), fp); /* buf 為 char array */

– fscanf 文法似 sscanf, 只是第一個參數為 fp

– fprintf 文法類 似 sprintf, 只是第一個參數為 fp (sprintf 第一個參數為 char array)

Page 76: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

76

如何安全讀入變數值 ? (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

...

Page 77: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

77

如何安全讀入變數值 ? (7/8)

在 C++ 程式檔案讀寫 (File I/O)

• 使用 fstream, ifstream, ofstream

ifstream myf("ggg.dat");

myf.getline(buf, sizeof(buf);

// 這樣整列讀入 // 然後用類似在 C 程式的處理方式 // 也可以這樣 : myf >> mydata; // 不好 (?)

Page 78: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

78

如何安全讀入變數值 ? (8/8)

其他注意事項 gets 讀入的與 fgets 讀入的 資料有差 !

用 fgets( ) 讀入的尾部可能有 newline必要時可以寫一個 void chop(char*x) 把字串 x 尾部的 newline “咬” 掉

cin.getline(buf, sizeof(buf)); 讀入的比較像用 gets(buf); 讀入的 , 字串中沒有 newline

多個 data 可用 sscanf 或是用 strtok 切開 strtok( ) function 在多 thread 時有問題 , 請改用新的標準 C 函數 strsep( )

Page 79: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

79

Writing data to a file (1/2)

Glen CowanRHUL Physics Computing and Statistical Data Analysis

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 myOutput; // Now open a new file... myOutput.open("myDataFile.dat"); // check that operation worked... if ( myOutput.fail() ) { cout << "Sorry, couldn’t open file" << endl; exit(1); // from cstdlib } // if ...

Page 80: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

80

Writing data to a file (2/2)

Glen CowanRHUL Physics Computing and Statistical Data Analysis

Now the ofstream object behaves like cout:

for (int i=1; i<=n; i++){ myOutput << i << "\t" << i*i << endl;}

Note use of tab character \t for 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., myOutput.setf(ios::fixed);

myOutput.precision(4);...

Page 81: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

81

File access modes

Glen CowanRHUL Physics Computing and Statistical Data Analysis

The previous program would overwrite an existing file.To append an existing file, we can specify:

myOutput.open("myDataFile.dat", ios::app);

This is an example of a file access mode. Another useful one is:

myOutput.open("myDataFile.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:

myOutput.open("myDataFile.dat", ios::bin | ios::app);

Many options, also for ifstream. Google for details.

Page 82: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

82

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 >> myVariable;

Gets stream from keyboard and puts it into myVariable

• 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)

Page 83: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

83

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 displayedstd::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 statementstd::cout << "Hello " << "there" << std::endl;

Page 84: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

84

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

Page 85: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

85

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 stor

es 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 de

limiter from the stream and does not store it in array– Null character inserted into array

Page 86: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

86

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 s

et• Stream manipulators: oct, hex, dec, setbase( ), setprecision( ),

setw( )

Page 87: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

87

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.

Page 88: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

88

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 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.

Page 89: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

89

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)

Page 90: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

90

ios flags for open Mode

causes all output to that file to be appended tothe 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.

causes the contents of the file to be destroyed ,and file size truncated to zero length.

this value causes the file to opened in binarymode, as opposed to the default text mode. Inbinary mode no character translation can occur.

ios::app

ios::ate

ios::in

ios::out

ios::trunc

ios::binary

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

Page 91: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

91

<iomanip> functions

setw(int w)setfill(int c)

leftright

setbase(int b)fixed

scientificshowpoint

setprecision(int d)skipws

showposboolalpha

Set field width to wSet the fill character to cFill characters are padded after the displayFill characters are padded beforeSet the numeric base to bDisplay floating-point values in decimal notationDisplay floating-point values in scientific notationValues are always shown with a decimal pointSet number of places accuracy to dWhitespace ignored during extractionsPositive numbers have a leading + signDisplay logical values symbolically as true/false

http://www.csie.nctu.edu.tw/~tsaiwn/oop/

Page 92: C++ 物件導向程式設計 Introduction to C++ with OOP

交通大學資訓工程學系 蔡文能

92

Thank You!Thank You!謝謝捧場 ; 下次見 !

[email protected]

蔡文能

http://www.csie.nctu.edu.tw/~tsaiwn/cpp/

02_ooa_ood.ppt