軟件設(shè)計(jì)課件:Lecture 07 C Operator Overloading_第1頁(yè)
軟件設(shè)計(jì)課件:Lecture 07 C Operator Overloading_第2頁(yè)
軟件設(shè)計(jì)課件:Lecture 07 C Operator Overloading_第3頁(yè)
軟件設(shè)計(jì)課件:Lecture 07 C Operator Overloading_第4頁(yè)
軟件設(shè)計(jì)課件:Lecture 07 C Operator Overloading_第5頁(yè)
已閱讀5頁(yè),還剩44頁(yè)未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

1、Lecture 07. C+ Operator OverloadingDesign and programming are human activities;forget that and all is lost.-Bjarne Stroustrup, 1991OutlineIntroductionClass PracticeMethods vs. Friend FunctionsUnary vs. Binary Case Study: ArrayOther Operator Overloadings(1)運(yùn)算符重載是對(duì)已有的運(yùn)算符賦予多重含義,使同一個(gè)運(yùn)算符作用于不同類型的數(shù)據(jù)時(shí),產(chǎn)生不同類

2、型的行為。C+允許同一運(yùn)算符具有多種不同運(yùn)算功能的機(jī)制。(2)為什么需要運(yùn)算符重載:C+中預(yù)定義了許多運(yùn)算符,能夠滿足用戶的一般應(yīng)用要求,但是其運(yùn)算的對(duì)象應(yīng)是基本數(shù)據(jù)類型,而不適用于用戶自定義數(shù)據(jù)類型(如類),這可以使用運(yùn)算符重載。(3)明智地使用操作符重載可以使類類型的使用像內(nèi)置類型一樣直觀(4)操作符的實(shí)質(zhì)是函數(shù)重載。IntroductionOperator overloading Use traditional operators with user-defined objectsStraightforward and natural way to extend C+Requires g

3、reat care When overloading is misused, programs become difficult to understand class Point public:Point(int xx=0,int yy=0) x=xx;y=yy; int getX();int getY(); /. private:int x; int y ; ; Point p1(1,1),p2(3,3),實(shí)現(xiàn)“p1 + p2”則需要編寫程序來(lái)說(shuō)明“+”如何作用于Point對(duì)象(p1, p2),即p1的私有成員 x,y 與p2的私有成員 x,y 分別相加這一功能。IntroductionU

4、se operator overloading to improve readabilityAvoid excessive or inconsistent usageFormatWrite function definition as normal(重載函數(shù)跟普通函數(shù)一樣,具有返回類型和形參表)Function name is keyword operator followed by the symbol for the operator being overloaded. operator+ would be used to overload the addition operator (+

5、).Fundamentals of Operator OverloadingAssignment operator (=) may be used with every class without explicit overloadingmemberwise assignment Same is true for the address operator (&)class MyClass public: . MyClass& operator=(const MyClass &rhs); . MyClass a, b; . b = a; / Same as b.operator=(a);Fund

6、amentals of Operator OverloadingMost of C+s operators can be overloaded有四個(gè)符號(hào)(+, -, * 和 &)既可作一元操作符又可作二元操作符,可以同時(shí)定義一元和二元操作符重載操作符不能改變?cè)僮鞣膬?yōu)先級(jí)、結(jié)合性或操作數(shù)目重載操作符必須具有至少一個(gè)類類型或枚舉類型的操作數(shù),也就是說(shuō)重載操作符不能重新定義用于內(nèi)置類型對(duì)象的操作符的含義,比如不能重載”+”號(hào)操作符用于兩個(gè)整數(shù)相加。Restrictions on Operator Overloading OutlineIntroductionClass PracticeMetho

7、ds vs. Friend FunctionsUnary vs. Binary Case Study: ArrayOther Operator OverloadingsWrite an overloading for the operator “*=” for this class class Point public:Point(int xx=0,int yy=0) x=xx;y=yy; int getX();int getY(); /. private:int x; int y; ; Point p1(1,1),p2(3,3),實(shí)現(xiàn)“p1 *= p2”,即p1的私有成員 x,y 與p2的私

8、有成員 x,y 分別相乘,并將結(jié)果分別賦于p1的私有成員。Class practiceOutlineIntroductionClass PracticeMethods vs. Friend FunctionsUnary vs. Binary Case Study: ArrayOther Operator OverloadingsOperator functions Can be member or non-member functionsOverloading the assignment operators i.e:(), , -,=Operator must be a member fun

9、ction Operator Functions as Class Members vs. as friend FunctionsOperator functions as member functionsLeftmost operand must be an object (or reference to an object) of the classIf left operand of a different type(與定義的class不一致), operator function must be a non-member functionA non-member operator fu

10、nction must be a friend if private or protected members of that class are accessed directly 如果需要訪問類的私有或者保護(hù)對(duì)象Operator Functions as Class Members vs. as friend FunctionsNon-member overloaded operator functionsEnable the operator to be commutative(可交換的),because the leftmost operand can be another type.

11、 HugeInteger bigInteger1; long int number;bigInteger1 = number + bigInteger1;orbigInteger1 = biginteger1 + number;Operator Functions as Class Members vs. as friend FunctionsFriend functionMember Functiona + boperator+(a,b)a.operator+(b)a+operator+(a,0)a.operator+(0)-aoperator-(a)a.operator-( )類成員的操作

12、符函數(shù)與其等價(jià)的友元函數(shù):Operator Functions as Class Members vs. as friend Functions友元運(yùn)算符函數(shù)無(wú)this指針,因而在函數(shù)體內(nèi)必須通過(guò)對(duì)象名來(lái)使用private成員數(shù)據(jù);一般將一元運(yùn)算符函數(shù)重載為類運(yùn)算符函數(shù)(“=”也必須)。因?yàn)橐辉\(yùn)算符時(shí)常需要用到this 指針(為什么?)一般將二元運(yùn)算符重載為友元運(yùn)算符函數(shù),以免出現(xiàn)使用錯(cuò)誤。因?yàn)闀r(shí)常需要操作數(shù)可交換“=”、“()”、“”和“-”不能重載為友元。Operator Functions as Class Members vs. as friend FunctionsOverload

13、ed operators Must have left operand of types ostream &, istream & respectivelyIt must be a non-member (friend) function (left operand not an object of the class)It must be a friend function if it accesses private data membersOverloading Stream-Insertion and Stream-Extraction Operators 語(yǔ)法:friend oper

14、ator(形參表) 函數(shù)體;Overloading Stream-Insertion and Stream-Extraction Operators both design and programming comply with the top-down & step-wised refinement methodologyfig18_03.cpp (1 of 3)fig18_03.cpp (2 of 3)fig18_03.cpp (3 of 3)Enter phone number in the form (123) 456-7890:(800) 555-1212The phone numb

15、er entered was: (800) 555-1212 OutlineIntroductionClass PracticeMethods vs. Friend FunctionsUnary vs. Binary Case Study: ArrayOther Operator OverloadingsOverloading unary operatorsAvoid friend functions and friend classes unless absolutely necessary. Use of friends violates the encapsulation of a cl

16、ass.As a member function:class String public: bool operator!() const; .; operator(形參表) 函數(shù)體;Overloading Unary OperatorsOverloaded binary operatorsNon-static member function, one argumentNon-member function (friend), two argumentsclass String public: const String &operator+=( const String & ); .; / en

17、d class Stringy += z; equivalent to y.operator+=(z);Overloading Binary OperatorsExampleclass Stringfriend const String &operator+=( String &, const String & );.; / end class Stringy += z; equivalent to operator+=(y,z);語(yǔ)法:friend operator(形參表) 函數(shù)體;Overloading Binary OperatorsOutlineIntroductionClass P

18、racticeMethods vs. Friend FunctionsUnary vs. Binary Case Study: ArrayOther Operator OverloadingsImplement an Array class with Range checkingArray assignmentArrays that know their sizeOutputting/inputting entire arrays with Array comparisons with = and !=Case Study: An Array classarray1.h (1 of 2)arr

19、ay1.h (2 of 2)why there are two operator methods here?array1.cpp (1 of 6)array1.cpp (2 of 6)array1.cpp (3 of 6)array1.cpp (3 of 6)array1.cpp (4 of 6)array1.cpp (5 of 6)array1.cpp (6 of 6)fig18_04.cpp (1 of 4)fig18_04.cpp (2 of 4)fig18_04.cpp (3 of 4)fig18_04.cpp (4 of 4)Array output (1 of 1)# of arr

20、ays instantiated = 0# of arrays instantiated = 2Size of array integers1 is 7Array after initialization: 0 0 0 0 0 0 0Size of array integers2 is 10Array after initialization: 0 0 0 0 0 0 0 0 0 0Input 17 integers:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17After input, the arrays contain:integers1: 1 2 3

21、 4 5 6 7integers2: 8 9 10 11 12 13 14 15 16 17Evaluating: integers1 != integers2They are not equalSize of array integers3 is 7Array after initialization: 1 2 3 4 5 6 7Array output (2 of 2)Assigning integers2 to integers1:integers1: 8 9 10 11 12 13 14 15 16 17integers2: 8 9 10 11 12 13 14 15 16 17Eva

22、luating: integers1 = integers2They are equal integers15 is 13Assigning 1000 to integers15integers1: 8 9 10 11 12 1000 14 15 16 17 Attempt to assign 1000 to integers115Assertion failed: 0 = subscript & subscript size, file Array1.cpp, line 95 abnormal program terminationCast operatorConvert objects i

23、nto built-in types or other objects Conversion operator must be a non-static member function.Cannot be a friend function形參表必須為空不能指定返回類型,但是必須顯式返回一個(gè)指定類型的值轉(zhuǎn)換函數(shù)采用如下通用形式:operator type();type 表示內(nèi)置類型名、類類型名或由類型別名定義的名字,對(duì)任何可作為函數(shù)返回類型的類型(除了 void 之外)都可以定義轉(zhuǎn)換函數(shù)。For user-defined class AA:operator char *() const;A:operator int() const;A:operator otherClass() const;When compiler sees (char *) s it calls s.operator char*()Converting between TypesOutlineIntroductionClass PracticeMethods vs. Friend FunctionsUnary vs. Binary Case Study: ArrayOther Operator OverloadingsThe compiler can call these functions t

溫馨提示

  • 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論