計算機程式 第十四單元 Polymorphism 授課教師:廖婉君教授...
-
Upload
samuel-walters -
Category
Documents
-
view
242 -
download
1
Transcript of 計算機程式 第十四單元 Polymorphism 授課教師:廖婉君教授...
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 條合理使用。
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
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;
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);
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;
版權聲明
6
頁碼 作品 版權圖示 來源 / 作者
1-6本作品轉載自 Microsoft Office 2007 多媒體藝廊,依據 Microsoft 服務合約及著作權法第 46 、 52 、 65 條合理使用。