Download presentation
Presentation is loading. Please wait.
Published byAugustus Watts Modified over 9 years ago
1
計算機程式 第十二單元 Operator Overloading II 授課教師:廖婉君教授 【本著作除另有註明外,採取創用 CC 「姓名標示 -非商業性-相同方式分享」台灣 3.0 版授權釋出】創用 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 條合理使用。 Microsoft 服務合約
2
Example 2 Fig.11.6 p.479
3
Example 3 Fig.11.7 p.480~482
4
Example 4 Fig.11.8 p.482~484
5
Converting between Types Cast operator (conversion operator) o Convert from One class to another A class to a built-in type (int, char, etc.) o Must be non-static member function o No need to specify return type Implicitly returns type to which you are converting 5
6
Converting between Types(cont.) Cast operator (conversion operator) o Example Prototype A::operator char *() const; o Cast class A to a temporary char * o static_cast (s) calls s.operator char *() o e.g., cout << s Also o A::operator int () const; o A::operator otherClass() const; 6
7
Case Study: String Class Build class String o String creation, manipulation Conversion constructor o Any single-argument constructor o Turns objects of other types into class objects Example: String s1( "happy" ); Overloading function call operator o Powerful (functions can take arbitrarily long and complex parameter lists) 7
8
Outline fig11_11.cpp 8 p.499-501
9
Overloading ++ and -- To distinguish prefix and postfix increment o Postfix increment has a dummy parameter An int with value 0 o Prototype (member function) Date operator++( int ); d1++ becomes d1.operator++( 0 ) o Prototype (global function) Date operator++( Date &, int ); d1++ becomes operator++( d1, 0 ) 9
10
Overloading ++ and -- (cont.) Return values o Prefix increment Returns by reference (Date &) lvalue (can be assigned) o Postfix increment Returns by value o Returns temporary object with old value rvalue (cannot be on left side of assignment) All this applies to decrement operators 10
11
版權聲明 11 頁碼作品版權圖示來源 / 作者 1-11 本作品轉載自 Microsoft Office 2007 多媒體藝廊,依據 Microsoft 服務合約及著作權法第 46 、 52 、 65 條合理使用。 2-4 、 8 Open Clip Art Library ,作者: aritztg ,本作品轉載自: http://openclipart.org/detail/3422/mouse-by-aritztg ,瀏覽日期: 2013/1/10 。 http://openclipart.org/detail/3422/mouse-by-aritztg 7 Open Clip Art Library ,作者: mazeo ,本作品轉載自: http://openclipart.org/detail/60205/crossword-letter-tiles-by-mazeo ,瀏覽日期: 2013/1/23 。 http://openclipart.org/detail/60205/crossword-letter-tiles-by-mazeo 9 Open Clip Art Library ,作者: Anonymous ,本作品轉載自: http://openclipart.org/detail/34693/architetto----tasto-2-by-anonymous , http://openclipart.org/detail/34693/architetto----tasto-2-by-anonymous 瀏覽日期: 2013/1/23 。
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.