Download presentation

Presentation is loading. Please wait.

Published byJayson Key Modified about 1 year ago

1
Chapter 13 Operator Overloading ( 运算符重载） §13.1 Introduction §13.2 Operator Functions §13.3 Overloading Simple Operators §13.4 Overloading “[]” §13.5 Overloading “ >” §13.6 Object conversion §13.7 Overloading “=” §13.8 Overloading “()” and Functor

2
§13.1 Introduction Operators （运算符） How about object variables? String operators 2 string s1 = "ABC"; string s2 = s1 + "DEF"; cout<

3
The Rational Class （分数） 3 1/2, 1/3, 11/12,… … b a Rational.cpp Run Rational.h TestRationalClass.cpp 分子 分母

4
Operation of the Rational Class 4 Rational Rational::add(Rational &secondRational) { long n = numerator * secondRational.getDenominator() + denominator * secondRational.getNumerator(); long d = denominator * secondRational.getDenominator(); return Rational(n, d); } Rational Rational::subtract(Rational &secondRational){ long n = numerator * secondRational.getDenominator() - denominator * secondRational.getNumerator(); long d = denominator * secondRational.getDenominator(); return Rational(n, d); } … cout<

5
Operator Functions （运算符函数） The functions to overload operators 5 bool Rational::operator< (Rational &secondRational) { if (this->compareTo(secondRational) < 0) return true; else return false; } if(r1 < r2) cout<<“r1 is less than r2.”<

6
Overloadable Operators 6 Unoverloadable Operators: ::. *? :#

7
§13.3 Overloading Simple Operators Relational Operators 7 bool Rational::operator< (Rational &secondRational){ if (this->compareTo(secondRational) < 0) return true; else return false; } bool Rational::operator< (Rational &secondRational){ long n = numerator * secondRational.getDenominator() – denominator * secondRational.getNumerator(); if (n < 0) return true; else return false; } A member function of Rational class. Parameter: usually pass-by-reference (can by value) one for a binary operator (The other one the object of the function) keyword Return type: the data type of “<”

8
Arithmetical Operators （算术运算符） 8 Rational Rational::operator+(Rational &secondRational){ return this->add(secondRational); } Return type: Rational, the data type of “+” To be used as an operand in complex operation!

9
Notes The left operand is fixed to be the operating object automatically c1 = c2 + c3 ; c1 = c2.operator+(c3); The number of parameters is determined by the operator itself You cannot change it Overloading does not change the operator precedence （优先级） and associativity （结合性） The (return) type of the operator function can be defined by you Usually the same class type to be operational in complex operation 9

10
Overloading Shorthand Operators 10 +=, -=, *=, /= Rational Rational::operator+=(Rational &secondRational) { *this = this->add(secondRational); return (*this); } Rational r1(2, 4); Rational r2 = r1 += Rational(2, 3); cout << "r1 is " << r1.toString() << endl; cout << "r2 is " << r2.toString() << endl;

11
Overloading Unary Operators 11 ‘+’ and ‘-’ --no parameters Rational Rational::operator-() { numerator *= -1; return *this; }

12
Overloading ++ and -- Prefix vs. Postfix 12 ++r1 r1++ Rational Rational::operator++() { numerator += denominator; return *this; } Rational Rational::operator++(){ Rational temp(numerator, denominator); numerator += denominator; return temp; } (int dummy){ Same signature, How to distinguish them? 哑元参数,the value is never used; It must be “int”. Same signature, How to distinguish them?

13
§13.4 Overloading “[]” The array subscript [] is an operator You can overload this operator to access the contents of the object using the array-like syntax For example, r[0]: to access numerator r[1]: to access denominator 13

14
Overloading “ [] ” 14 long Rational::operator[](const int &index) { if (index == 0) return numerator; else if (index == 1) return denominator; else { cout << "subscript error" << endl; exit(0); }

15
[] Accessor and Mutator The [] operator functions as both accessor and mutator. After adding this operator to the Rational class, the Rational class is mutable. 15 Rational r4(1, 2); r4[0] = 3; r4[1] = 4; long &Rational::operator[](const int &index)

16
§13.5 Overloading “ >” <<: stream insertion operator For sending an object to cout >>: stream extraction operator For reading values from cin Overload them? 16 Rational r4(1, 2); cout<

17
Overloading “ >” 17 Rational r4(1, 2); cout<

18
Overloading “ >” Making use of friendship! 18 friend ostream &operator<<(ostream &, Rational &); friend istream &operator>>(istream &, Rational &); ostream &operator<<(ostream &str, Rational &rational){ str << rational.numerator << " / " << rational.denominator; return str; } istream &operator>>(istream &str, Rational &rational){ cout << "Enter numerator: "; str >> rational.numerator; cout << "Enter denominator: "; str >> rational[1]; return str; } Other operators can also be overloaded as friends!

19
Friend: the left-hand operand as an argument Friend vs. Member C3 = C1 + C2 C3 = C1.operator+(C2) C3 = C1 + 2 C3 = C1.operator+(2) C3 = 2 + C1 C3 = 2.operator+(C1) ??? C3 = 2 + C1 C3 = operator+(2, C1) friend complex operator+(complex a, complex b); complex operator+(complex a, complex b) { return complex((a.x+b.x),(a.y+b.y)); }

20
Overloadable Operators Unoverloadable Operators: ::..*? :#sizeof A friend cannot be used: =( )[ ]->

21
§13.6 Object Conversion Convert a class type to other data types? Using operator functions 21 double i, j; i= ; double i; Rational r1; i= 2+r1;

22
Object Conversion Rational::operator double() { return 1.0 * getNumerator() / getDenominator(); } 22 Rational r1(1, 4); double d = r ; cout << "r is " << d << endl;

23
The New Rational Class 23 NewRational. cpp Run NewRational.h TestNewRationalClass

24
§13.7 Overloading “=” By default, “ = ” performs a memberwise copy For Rational class, it is OK. How about others? 24 Rational r1(1, 2); Rational r2(4, 5); r1 = r2; class Person{ private: int id; Date* birthDate; }; … p1 = p2;

25
Overloading “=” “The rule of three” Copy constructor Destructor “=” 25 DefaultAssignmentDemo Run

26
Overloading “=” 26 const Person Person::operator=(const Person &p){ id = p.id; Date *pt=p.getBirthDate(); birthDate = new Date(*pt); return *this; }

27
§13.8 Overloading “()” and Functor “()”: calling a function “()” as a member of a class? 27 class Comparer{ public: bool operator()(int v){ return v>60; } }; int main(){ Comparer cmp; int i; cin>>i; if(cmp(i)) cout<<"Yes, passed!\n"; else cout<<"No, failed!\n"; } bool Comparer(int v){ return v>60; }; Object acting as a function Function object (functor, 仿函数 )

28
Functor as Parameter To count an integral array’s elements that satisfy some condition, e.g. >=60 >=85 >=90 28 int countArray(int a[], int s, int th); int countArray(int a[], int s); int countArrayIf(int a[], int s, Comparer cmp);

29
Functor as Parameter 29 class Comparer{ public: Comparer(int val = 60):vs(val){} int operator()(int); private: int vs; }; int main(){ int a[3] = {100,54,76}; Comparer cmp(70); cout<~~
~~

30
Function Object vs. Function Pointer Please learn by yourself, if you want. Function pointer ( 函数指针 ) Callback function ( 回调函数 ) 30 void callBack(void (*ptr)(int)){ int x; while(true){ cin>>x; if(x==-999) break; (*ptr)(x); } void (*pf)(int); void glFun(int a){ if(a>0) cout<<“Y\n”; else cout<<“N\n”; } void main() { pf=glFun; (*pf)(100); callBack(pf); }

31
A Summary Operator functions to overload operators Overloading various operators Return type Parameter var++ vs. ++var Type conversion Overloading as member Overloading as friend Functor 31

32
Homework Questions 1.Is the following code a correct implementation of “+=”? 2.Why do you need to overload “=”? 32 Rational Rational::operator+=(Rational &secondRational){ this->add(secondRational); return this; }

Similar presentations

© 2017 SlidePlayer.com Inc.

All rights reserved.

Ads by Google