計算機程式 第十四單元 Polymorphism 授課教師:廖婉君教授...

6
計計計計計 第第第第第 Polymorphism 第第第第 第第第第第 計計 CC 計計計計 計計計計計 計計計計計計 計計 -- 3.0 計計計計第第第第第第第第 C++ How to Program, 7/e, Harvey M. Deitel and Paul J. Deitel, both from Deitel & Associates, Inc. © 2010 第第第第第第第第第第 第第第第第第第第 ,。 1 第第第第第第 Microsoft Office 2007 第第 第第第 第第 體, Microsoft第第第第 第第第第第第 46 52 65 第第第第第

Transcript of 計算機程式 第十四單元 Polymorphism 授課教師:廖婉君教授...

Page 1: 計算機程式 第十四單元 Polymorphism 授課教師:廖婉君教授 【本著作除另有註明外,採取創用 CC 「姓名標示 -非商業性-相同方式分享」台灣

1

計算機程式第十四單元 Polymorphism

授課教師:廖婉君教授

【 本 著 作 除 另 有 註 明 外 , 採 取 創用 CC

「姓名標示-非商業性-相同方式分享」台灣 3.0

版授權釋出】本課程指定教材為 C++ How to Program, 7/e, Harvey M. Deitel and Paul J. Deitel, both from Deitel & Associates, Inc. ©

2010 。 本講義僅引用部分內容,請讀者自行準備。本作品轉載自 Microsoft Office 2007 多媒體藝廊,依據Microsoft服務合約及著作權法第 46 、 52 、 65 條合理使用。

Page 2: 計算機程式 第十四單元 Polymorphism 授課教師:廖婉君教授 【本著作除另有註明外,採取創用 CC 「姓名標示 -非商業性-相同方式分享」台灣

2

An Overview

• Polymorphism o To associate many meanings to one function name by means of the late

binding (runtime) mechanism

o Program in general, execute in specific

• Must work with class hierarchy

• Must work off base-class pointer or reference handles, not off name

handles

o Polymorphism: virtual function + late binding (i.e., run-time)/ dynamic

binding

Page 3: 計算機程式 第十四單元 Polymorphism 授課教師:廖婉君教授 【本著作除另有註明外,採取創用 CC 「姓名標示 -非商業性-相同方式分享」台灣

3

Virtual function• To make a function virtual is to tell the complier that “I

don’t know how the function is implemented. Wait until it is used in a program, and then get the implementation from the object instance.”

• e.g., virtual double bill() const; • Pure virtual function

o virtual double bill() const =0;

Page 4: 計算機程式 第十四單元 Polymorphism 授課教師:廖婉君教授 【本著作除另有註明外,採取創用 CC 「姓名標示 -非商業性-相同方式分享」台灣

4

More on Class Hierarchy• Upcasting is ok,

o e.g., vpet = vdog;

• Downcasting is not permitted unless dynamic_cast (it only works for pointer type) is explicitly used.

• e.g., (downcasting)

Pet *ppet; ppet=new Dog;

Dog *pdog = dynamic_cast<Dog *>(ppet);

Page 5: 計算機程式 第十四單元 Polymorphism 授課教師:廖婉君教授 【本著作除另有註明外,採取創用 CC 「姓名標示 -非商業性-相同方式分享」台灣

5

Virtual Destructor

• Make destructor in the base class virtual (then, the

destructor for the derived class is called), otherwise,

only the destructor for the base class is called. o e.g., SomeCass *p= new SomeClass;

delete p;

o e.g., Base *pBase = new Derived;

delete pBase;

Page 6: 計算機程式 第十四單元 Polymorphism 授課教師:廖婉君教授 【本著作除另有註明外,採取創用 CC 「姓名標示 -非商業性-相同方式分享」台灣

版權聲明

6

頁碼 作品 版權圖示 來源 / 作者

1-6本作品轉載自 Microsoft Office 2007 多媒體藝廊,依據 Microsoft 服務合約及著作權法第 46 、 52 、 65 條合理使用。