Transcript
Page 1: Chapter 7 Operator Overloading and Type Conversions

Chapter 7Operator Overloading and Type Conversions

§7.1 Defining Operator Overloading

§7.2 Overloading Unary Operators

§7.3 Overloading Binary Operators

§7.4 Overloading Other Operators

§7.5 Type Conversions

Page 2: Chapter 7 Operator Overloading and Type Conversions

§7.1 Introduction

Operators (运算符)

How about object variables? String operators

+ - * / % ^ & | ~ ! = < > += -= *= /= %= ^= &= |= <<

>> >>= <<= == != <= >= && || ++ --

->* , -> [] () new delete

2

string s1 = "ABC";string s2 = s1 + "DEF";cout<<s1<<endl;cout<<(s1>s2)<<endl;...

string s1 = "ABC";string s2 = s1 + "DEF";cout<<s1<<endl;cout<<(s1>s2)<<endl;...

int a = 1;int b = a+1;if(a<b) cout<<a;

int a = 1;int b = a+1;if(a<b) cout<<a;

class C{};C c, a, b;c = a + b;//?

class C{};C c, a, b;c = a + b;//?

Page 3: Chapter 7 Operator Overloading and Type Conversions

The Rational Class (分数) Rational

-numerator: long

-denominator: long

+Rational()

+Rational(numerator: long, denominator: long)

+getNumerator(): long

+getDenominator(): long

+add(secondRational: Rational &): Rational

+subtract(secondRational: Rational &): Rational

+multiply(secondRational: Rational &): Rational

+divide(secondRational: Rational &): Rational +compareTo(secondRational: Rational &): int

+equals(secondRational: Rational &): bool

+intValue(): int

+doubleValue(): double

+toString(): string

-gcd(n: long, d: long): long

3

1/2, 1/3, 11/12,…1/2, 1/3, 11/12,…

3 4 23 83 4 23 8

4 7 32 9…4 7 32 9…

bbaa

Rational.cppRational.cpp

RunRun

Rational.hRational.h

TestRationalClass.cppTestRationalClass.cpp

分子分母

Page 4: Chapter 7 Operator Overloading and Type Conversions

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);

}…

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<<r1.toString()<< " + "<< r2.toString()<< " = "<< r1.add(r2).toString()<< endl; cout<<r1.toString()<< " - "<< r2.toString()<< " = "<< r1.subtract(r2).toString()<< endl; …

cout<<r1.toString()<< " + "<< r2.toString()<< " = "<< r1.add(r2).toString()<< endl; cout<<r1.toString()<< " - "<< r2.toString()<< " = "<< r1.subtract(r2).toString()<< endl; …

cout << r1<< " + " << r2 << " = "<< r1+r2<< endl; cout << r1<< " - " << r2 << " = "<<r1-r2<< endl; …

cout << r1<< " + " << r2 << " = "<< r1+r2<< endl; cout << r1<< " - " << r2 << " = "<<r1-r2<< endl; …

Page 5: Chapter 7 Operator Overloading and Type Conversions

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.”<<endl;if(r1 < r2) cout<<“r1 is less than r2.”<<endl;

if(r1.operator<(r2)) cout<<“r1 is less than r2.”<<endl;if(r1.operator<(r2)) cout<<“r1 is less than r2.”<<endl;

Page 6: Chapter 7 Operator Overloading and Type Conversions

Defining Operator Overloading

General form

Can also be friends:

6

type classname :: operator op(arglis){ Function body // task defined}

vector operator+ (vector); // vector additionvector operator- (); // unary minusfriend vector operator+ (vector, vector);//vector additionfriend vector operator- (vector); // unary minus

Page 7: Chapter 7 Operator Overloading and Type Conversions

§7.2 Overloading Unary Operators

‘+’ and ‘-’ --no parameters

7

Overloading Unary MinusOverloading Unary Minus

void space :: operator-(){ x=-x; y=-y; z=-z;}

//declarationfriend void operator-(space &s);//definition void operator-(space &s) { s.x=-s.x; s.y=-s.y; s.z=-s.z;}

Page 8: Chapter 7 Operator Overloading and Type Conversions

Overloading ++ and --

Prefix vs. Postfix

8

++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?

Page 9: Chapter 7 Operator Overloading and Type Conversions

Overloading “[]”

The array subscript [] is an operator Can be overloaded to access the members of an

object

9

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

}

int main(){ Rational r(2,3); cout << r[0]/r[1];

}

Page 10: Chapter 7 Operator Overloading and Type Conversions

[] Accessor and Mutator The [] operator functions as both accessor and

mutator. After adding this operator to the Rational class,

the Rational class is mutable.

10

Rational r4(1, 2); r4[0] = 3; r4[1] = 4;

Rational

-numerator: long

-denominator: long

+Rational()

+Rational(numerator: long, denominator: long)

+getNumerator(): long

+getDenominator(): long

+add(secondRational: Rational &): Rational

+subtract(secondRational: Rational &): Rational

+multiply(secondRational: Rational &): Rational

+divide(secondRational: Rational &): Rational +compareTo(secondRational: Rational &): int

+equals(secondRational: Rational &): bool

+intValue(): int

+doubleValue(): double

+toString(): string

-gcd(n: long, d: long): long

long &Rational::operator[](const int &index)

Page 11: Chapter 7 Operator Overloading and Type Conversions

§7.3 Overloading Binary Operators

11

Overloading + operatorOverloading + operator

//functional notationC = sum ( A, B);

//arithmetic notationC = A + B;

complex complex :: operator+(complex c){ complex temp; temp.x = x + c.x; temp.y = y + c.y; return(temp); }

Page 12: Chapter 7 Operator Overloading and Type Conversions

Operands of Binary Operators

Features: Only one complex argument Returns a complex type value A member function of complex

12

complex complex :: operator+(complex c){ complex temp; temp.x = x + c.x; temp.y = y + c.y; return(temp); } C3 = C1 + C2;

C3 = C1.operator+(C2);

Page 13: Chapter 7 Operator Overloading and Type Conversions

Operands of Binary Operators

13

complex complex :: operator+(complex c){ complex temp;

temp.x = c.x + x; temp.y = c.y + y;

return(temp);}

4.10

6.20

temp

4.10 x

6.20 y

C3

2.50 x

3.50 y

C1

1.60 x

2.70 y

C2;+=

Fig.7.1 ⇔ Implementation of the overload + operator

Page 14: Chapter 7 Operator Overloading and Type Conversions

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

14

Page 15: Chapter 7 Operator Overloading and Type Conversions

§7.4 Overloading Other Operators

15

+=, -=, *=, /=

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;

Page 16: Chapter 7 Operator Overloading and Type Conversions

Overloading “=”

By default, “=” performs a memberwise copy For Rational class, it is OK.

How about others?

16

Rational r1(1, 2);

Rational r2(4, 5);

r1 = r2; class Person{private: int id; Date* birthDate; };…p1 = p2;

Page 17: Chapter 7 Operator Overloading and Type Conversions

Overloading “=”

“The rule of three” Copy constructor Destructor “=”

17

person1: Person

id = 111

birthDate

111

Memory : BirthDate

year = 1963 month = 5 day = 3 reference

person2: Person

id = 111

birthDate

111

Memory

reference

Page 18: Chapter 7 Operator Overloading and Type Conversions

Overloading “=”

18

const Person Person::operator=(const Person &p){id = p.id;Date *p=p.getBirthDate();birthDate = new Date(*p);return *this;

}

Page 19: Chapter 7 Operator Overloading and Type Conversions

Friend: the left-hand operand as an argument

19

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)); }

Page 20: Chapter 7 Operator Overloading and Type Conversions

Two versions p = 2 * m;//equivalent to p = operator*(2,m)

q = n * 2;//equivalent to q = operator*(n,2) By overloading >> and << using functions:

friend istream& operator>>(istream&, vector&);

friend ostream& operator<<(ostream&, vector&);

vector variables in input and output statements can be used like simple variables

20

Overloading >> and <<

Overloading as friends.cppOverloading as friends.cpp

Page 21: Chapter 7 Operator Overloading and Type Conversions

Manipulation of Strings To define operators to manipulate the strings For example:

string3 = string1 + string2; if( string1 >= string2 ) string = string1;

An example program overloads + and <=

21Mathematical operations on stringsMathematical operations on strings

// overloading + operatorString operator+(const String &s, const String &t){ String temp; temp.len = s.len + t.len; temp.p = new char[temp.len+1]; strcpy(temp.p,s.p); strcat(temp.p,t.p); return temp;}

// overloading <= operatorint operator<=(const String &s, const String &t){

int m = strlen(s.p);int n = strlen(t.p);if(m <= n) return(1);else return(0);

}

Page 22: Chapter 7 Operator Overloading and Type Conversions

Overloadable Operators

22

+ - * / % ^ & | ~ ! = < > += -= *= /= %= ^= &= |= <<

>> >>= <<= == != <= >= && || ++ --

->* , -> [] () new delete

Unoverloadable Operators:

:: . .* ? : # sizeof

Unoverloadable Operators:

:: . .* ? : # sizeof

A friend cannot be used:

= ( ) [ ] ->

A friend cannot be used:

= ( ) [ ] ->

Page 23: Chapter 7 Operator Overloading and Type Conversions

§7.5 Type Conversions

Automatic type conversion for built-in types Constants and variables of different types are mixed in

an expression Right type of an assignment operator “=“ to the left

For example,int m;

float x = 3.14159;

m = x; What happens when they are user-defined data

types?

Using Casting operator or Constructor

23

Page 24: Chapter 7 Operator Overloading and Type Conversions

Three types of situations

A. Conversion from basic type to class type

B. Conversion from class type to basic type

C. Conversion from one class type to another class type

24

Page 25: Chapter 7 Operator Overloading and Type Conversions

Basic to Class Type

Implemented by using constructors with single argument

25

string::string (char * a){ length = strlen(a); p = new char[length+1]; strcpy(p, a);}

string s1,s2;char* name1 = “IBM PC”;char* name2 = “Apple”;s1 = string(name1);s2 = name2;

Page 26: Chapter 7 Operator Overloading and Type Conversions

Class to Basic Type

By defining an overloaded casting operator Usually referred to as a conversion function:

26

operator typename(){ ...... ......(Function statements)}

Rational::operator double(){ return numerator/denominator;}

int main(){ Rational r(2,3); double d = r;}

string:: operator char*(){ return (p);}

Page 27: Chapter 7 Operator Overloading and Type Conversions

Notes on class basic type

1. It must be a class member

2. It must not specify a return type

3. It must not have any arguments

27

Page 28: Chapter 7 Operator Overloading and Type Conversions

One Class to Another Class Type By either a constructor or a conversion function

28

objx = objy // Y is a source class

Casting operator function

Data access functions

Constructor function

Class X

Argument of type Y

Class Y

Conversion here (destination class)

Conversion here (source class)

Class Y

Converted value of type X

Fig.7.2 ⇔ Conversion between object

Page 29: Chapter 7 Operator Overloading and Type Conversions

An Example of Class to Class

A data conversion example From invent1 to invent2

29

Data conversionsData conversions

//constructor for conversion//invent2(invent1 p){ code = p.getcode(); value =p.getitems() * p.getprice();

}

//operator function for conversionoperator invent2(){ invent2 temp; temp.code = code; temp.value = price * items; return temp; }

Page 30: Chapter 7 Operator Overloading and Type Conversions

Summary of all the three conversions

30

Conversion requiredConversion takes place in

Source class Destination class

Basic → Class Not applicable Constructor

Class → Basic Casting operator Not applicable

Class → Class Casting operator Constructor

Page 31: Chapter 7 Operator Overloading and Type Conversions

Summary

Operator functions to overload operators Overloading as member or friend Overloading unary, binary operators

Operands? Overloading other operators Type conversion

31

Page 32: Chapter 7 Operator Overloading and Type Conversions

Review Questons

Q7.3 Q7.7 Q7.8

32


Top Related