软件设计课件:Lecture 07 C Operator Overloading_第1页
软件设计课件:Lecture 07 C Operator Overloading_第2页
软件设计课件:Lecture 07 C Operator Overloading_第3页
软件设计课件:Lecture 07 C Operator Overloading_第4页
软件设计课件:Lecture 07 C Operator Overloading_第5页
已阅读5页,还剩44页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

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)运算符重载是对已有的运算符赋予多重含义,使同一个运算符作用于不同类型的数据时,产生不同类

2、型的行为。C+允许同一运算符具有多种不同运算功能的机制。(2)为什么需要运算符重载:C+中预定义了许多运算符,能够满足用户的一般应用要求,但是其运算的对象应是基本数据类型,而不适用于用户自定义数据类型(如类),这可以使用运算符重载。(3)明智地使用操作符重载可以使类类型的使用像内置类型一样直观(4)操作符的实质是函数重载。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),实现“p1 + p2”则需要编写程序来说明“+”如何作用于Point对象(p1, p2),即p1的私有成员 x,y 与p2的私有成员 x,y 分别相加这一功能。IntroductionU

4、se operator overloading to improve readabilityAvoid excessive or inconsistent usageFormatWrite function definition as normal(重载函数跟普通函数一样,具有返回类型和形参表)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有四个符号(+, -, * 和 &)既可作一元操作符又可作二元操作符,可以同时定义一元和二元操作符重载操作符不能改变原操作符的优先级、结合性或操作数目重载操作符必须具有至少一个类类型或枚举类型的操作数,也就是说重载操作符不能重新定义用于内置类型对象的操作符的含义,比如不能重载”+”号操作符用于两个整数相加。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),实现“p1 *= p2”,即p1的私有成员 x,y 与p2的私

8、有成员 x,y 分别相乘,并将结果分别赋于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 如果需要访问类的私有或者保护对象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、符函数与其等价的友元函数:Operator Functions as Class Members vs. as friend Functions友元运算符函数无this指针,因而在函数体内必须通过对象名来使用private成员数据;一般将一元运算符函数重载为类运算符函数(“=”也必须)。因为一元运算符时常需要用到this 指针(为什么?)一般将二元运算符重载为友元运算符函数,以免出现使用错误。因为时常需要操作数可交换“=”、“()”、“”和“-”不能重载为友元。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 语法:friend oper

14、ator(形参表) 函数体;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(形参表) 函数体;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);语法:friend operator(形参表) 函数体;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形参表必须为空不能指定返回类型,但是必须显式返回一个指定类型的值转换函数采用如下通用形式:operator type();type 表示内置类型名、类类型名或由类型别名定义的名字,对任何可作为函数返回类型的类型(除了 void 之外)都可以定义转换函数。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. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论