Operator Overloading Chapter 8 1

Download Report

Transcript Operator Overloading Chapter 8 1

Operator Overloading
Chapter 8
1
2
In this Chapter ...
Overloading Operators
Friend Functions
3
Introduction
We manipulate class objects with
member function calls
 This is awkward with classes which
do mathematics
 Would be easier to add two class
objects with c3 = c1 + c2
rather than c3 = c1.add(c2)

4
Introduction
In this chapter we enable C++
operators to do manipulations on
class objects
 This is called operator overloading
 Actually we have seen it done
already

– << is a bitwise shift operator
– it is overloaded to act as an insertion to
a stream operator
5
Fundamentals of Operator
Overloading
C++ does not allow new operators
(the symbols themselves) to be
created
 It does allow existing operators to be
redefined (overloaded) to have new
meaning for a specific class objects
 We already use the + and - in
overloaded fashion when we add or
subtract ints, floats, doubles, etc

6
Fundamentals of Operator
Overloading -- Exceptions

Assignment operator =
– may be used without explicit
overloading
– possible (and sometimes important) to
explicitly overload the = operator

Address operator &
– simply returns address of an object, no
matter what the type
– but can also be overladed
7
Example

Given a class:

To overload +
class Complex {
public:
Complex::Complex();
. . .
private:
float realpart,
imagpart; } ;
friend Complex operator+ (Complex, Complex);

Implementation
{
Complex temp;
temp.a = c2.a + c1.a;
temp.b = c2.b + c1.b;
return temp; }
Goes in implementation file
8
Example
This example
class Complex {
a friend function friend Complex operator+
(Complex, Complex);
neither public
public:
nor private
Complex::Complex();
. . .
 Returns value of
private:
type Complex
float realpart,
imagpart; } ;
 Receives two
values of type Complex as parameters

9
Example
Complex operator+(Complex c1, Complex c2)
{ Complex temp;
temp.realpart=c2.realpart +c1.realpart
temp.imagpart=c2.imagpart +c1.imagpart;
return temp; }

Use a local Complex, temp
– for preliminary addition
– enables returning a value of type
Complex
10
Restrictions on Operator
Overloading

Precedence of operator cannot be
changed by overloading
– use parentheses to force order of
overloaded operators in an expression

Note Figures 8.1 & 8.2 for operators
which can and cannot be overloaded
– These cannot
.
.*
::
?:
sizeof
11
Restrictions on Operator
Overloading
Associativity of an operator cannot
be changed by overloading
 Number of operands an operator
takes cannot be changed
 Cannot create new operators

– can only change meaning (overload)
existing operators

Overloading works only with userdefined types
12
Restrictions on Operator
Overloading

Overloading the + does not
automatically overload the +=
– similar with -, *, etc.

Possible (advisable) to use an
overloaded + to implement an
overloaded +=
13
Class Members vs Friend Functions

Operator functions can be
– member functions
– non member (friend) functions
Member functions use the this
pointer to access one of their class
object arguments
 Usage remains the same in the call,
either way

14
Which is Best?

As a member function ...
– leftmost operand must be a class object
of the operator's class

As a nonmember function
– leftmost operant may be object of
different class or built in type
– must be friend function to access
private or protected class members
15
Class Members vs Friend Functions

Overloaded << must have left operand of
type ostream &
– requires a friend function

Overloaded >> must have left operand of
type istream &
 Unary function would require member
function (if no parameters)
 Commutative operator better to use friend
function
16
Stream-Insertion Operators
Already see << overloaded for
ostream class
 Can also be overloaded for userdefined types
 Note examples in figure 8.3, pg 469

– uses friend function
– note syntax
17
Stream-Insertion Operators

Source code has
cin >> phone;

Compiler changes to
operator>> (cin, phone);
Name of
function
Name of
input stream
Name of object
instance
18
Stream-Extraction Operators

Note use of friend functions
– Required because object of class
PhoneNumber appears on right

Note parameter list for
operator<< specified as const
– PhoneNumber merely output

operator>> not const
– PhoneNumber modified during input
19
Overloading Unary Operators

Can be overloaded as
– non-static member function
• (so they can access non-static data)
– no arguments
class String{
public:
bool operator!( ) const;
// will determine if
// object is empty
. . .;
20
Overloading Unary Operators

Unary function can also be
– non-member function
– with one argument
class String{
friend bool operator!(const String &);
// will determine if
// object is empty
. . .;
Optional -- may
not be needed
in this example.
21
Overloading Binary Operators

Can be overloaded as
– non-static
– member function
– one argument
class String {
public:
const String &operator+= (const String &);
// for string concatenation
// y += z
=> y.operator+=(z);
. . .
22
Overloading Binary Operators

Also can be declared as …
– non member function
– two arguments
– one object must be class object or
reference to class object
class String {
friend const String &operator+= (String &,
const String &);
// for string concatenation
// y += z
=> operator+=(y,z);
. . .
23
An Array Class -- Figure 8.4, pg 474

Note features
–
–
–
–
–

overloaded friend operator functions for I/O
constructors, destructors
accessor functions (size and [ ])
comparison operators
static counter variable, accessor
Note that element values are not stored in
the class -- they are in the dynamically
allocated memory
24
When a Constructor is Called and
Values Copied
When a value parameter is used
 At declaration and initialization
Rational r3 = r1;
 Return of a function value

These require a special kind of
constructor …
a "copy constructor"
25
Copy Constructor

Initializes an array
– makes a copy of an existing object

Array object is a pointer to dynamically
allocated memory
– constructor without copy would create a
second pointer to same location

Needed when
– value parameter, function value return,
initializing an object with value of another
26
Copy Constructor
New allocation of memory and copy
of initializing contents required
 New pointer alone would point to
same location as initial object
 First destructor to execute would
delete memory
 Other pointer becomes undefined

– a "dangling pointer"
27
Copy Constructor

Any class which uses dynamically
allocated memory should have …
– copy constructor
– constructor
– destructor
– overloaded assignment operator

Possible to make assignment & copy
constructor private
– prevents class objects from being copied
28
Converting Between Types

Often done when mixing floats and
ints in expressions

Occasionally needed in user defined
types
– compiler must be told how to do the
conversion

Conversion operator (or cast
operator) can be declared
– must be non-static, cannot be friend
29
Converting Between Types

Given user defined class Snarf
Snarf::operator float( ) const;
Snarf::operator Blat( ) const;

This declares two overloaded cast
operators
– an overloaded cast operator to create a
temporary float object out of a Snarf object
– another to create a temporary Blat object
30
Converting Between Types

Note that no return type is specified
Snarf::operator float( ) const;
Snarf::operator Blat( ) const;
– return type is the cast type (float, or Blat in
this example)

Compiler can call the conversion (or
cast) operator automatically when it
sees it needs it
– for example cout << aSnarf; // cast to float
31
String Class - Fig 8.5, pg 485

Note features
– I/O overloaded operators
– constructors, destructor
– comparison
– assignment, concatenation
– subscript operators
– substring operators
32
Overloading ++ and -Problem is how to distinguish
between the pre- and post-increment
versions
 Given Date object, d1

– Compiler sees ++d1
– Calls the function d1.operator++( )
Date &operator++( );
Pre-increment
version
33
Overloading ++ and -Compiler is designed to take
d1++
and convert it to
d1.operator++( 0 )
 The 0 is a "dummy" value
 Prototype would be

Date &operator++( int );
34
Date Class
Demonstrates the pre- and post
increment operators
 Note use of private utility function

– used only by members of class Date

See fig 8.6 and hear audio
explanation on CD-rom