18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer...

46
18-1 Computing Fundamentals Computing Fundamentals with C++ with C++ Object-Oriented Programming and Design, Object-Oriented Programming and Design, 2nd Edition 2nd Edition Rick Mercer Rick Mercer Franklin, Beedle & Associates, 1999 Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8 ISBN 1-887902-36-8 Presentation Copyright 1999, Franklin, Beedle & Associates Presentation Copyright 1999, Franklin, Beedle & Associates Students who purchase and instructors who adopt Students who purchase and instructors who adopt Computing Computing Fundamentals with C++, Object-Oriented Programming and Design Fundamentals with C++, Object-Oriented Programming and Design by Rick Mercer by Rick Mercer are welcome to use this presentation as long as this copyright are welcome to use this presentation as long as this copyright notice remains intact. notice remains intact.

Transcript of 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer...

Page 1: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-1

Computing Fundamentals with C++Computing Fundamentals with C++Object-Oriented Programming and Design, 2nd EditionObject-Oriented Programming and Design, 2nd Edition

Rick MercerRick Mercer

Franklin, Beedle & Associates, 1999Franklin, Beedle & Associates, 1999

ISBN 1-887902-36-8ISBN 1-887902-36-8

Presentation Copyright 1999, Franklin, Beedle & Associates Presentation Copyright 1999, Franklin, Beedle & Associates Students who purchase and instructors who adopt Students who purchase and instructors who adopt Computing Fundamentals with C++, Computing Fundamentals with C++, Object-Oriented Programming and Design Object-Oriented Programming and Design by Rick Mercer are welcome to use this by Rick Mercer are welcome to use this

presentation as long as this copyright notice remains intact.presentation as long as this copyright notice remains intact.

Page 2: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-2Chapter 18Chapter 18Operator OverloadingOperator Overloading

Chapter ObjectivesChapter Objectives overload != and < for any state object you want overload != and < for any state object you want

contained in a standard container contained in a standard container vector listvector list

perform complex arithmeticperform complex arithmetic overload << and >> so you can output or input any overload << and >> so you can output or input any

new class of objects that you developnew class of objects that you develop

Page 3: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-3 C++ Operator OverloadingC++ Operator Overloading

Built-in types (Built-in types (int doubleint double) define ) define operators operators < == != > <= >= + - / < == != > <= >= + - /

Operator overloading: operators have Operator overloading: operators have different meanings for different operands:different meanings for different operands:

ExpressionExpression 2 + 5 2 + 5 "2" + "5" "2" + "5" 2 / 52 / 52.0 / 5.0 2.0 / 5.0

Evaluates to7

"25"0

0.4

Page 4: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-4 Syntactic sugarSyntactic sugar

Operator overloading provides easier to read Operator overloading provides easier to read code: code:

Employee e1, e2;Employee e1, e2; if(e1.lessThan(e2)) if(e1.lessThan(e2)) // no operator overloading needed to do this// no operator overloading needed to do this

oror

if(e1 < e2) if(e1 < e2) // operator overloading for < must have// operator overloading for < must have // been done in class Employee// been done in class Employee

Page 5: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-5 Some standard classes doSome standard classes do

Overloaded operators allow your own Overloaded operators allow your own classes to "look like" the built-in typesclasses to "look like" the built-in types

Some Some standardstandard C++ classes overload some C++ classes overload some operators operators string and complex for example string and complex for example

string s1, s2;string s1, s2; cin >> s1 >> s2;cin >> s1 >> s2;if(s1 < s2)if(s1 < s2)

s1 += s2;s1 += s2;else else

s2 = s1 + s2; s2 = s1 + s2; // perform s2 += s1;// perform s2 += s1;cout << s2;cout << s2;

Page 6: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-6 Our own classes couldOur own classes could

But what about programmer defined But what about programmer defined classes such as classes such as CDCD, , bankAccountbankAccount, and , and DateDate?? Wouldn't it be nice if you could overload? Wouldn't it be nice if you could overload?

see Datesee Date Do you need to?Do you need to?

Yes, if you want to use the STLYes, if you want to use the STL

Page 7: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-7 Date overloads Date overloads -- and and ++

Consider adding or subtracting Date objectsConsider adding or subtracting Date objects const Date today; const Date today; // Default is today's date// Default is today's date Date graduationDay(5, 14, 1999);Date graduationDay(5, 14, 1999); int collegeDaysLeft = graduationDay - today;int collegeDaysLeft = graduationDay - today;

Date warrantyExpires; Date warrantyExpires; warrantyExpires = today + 90;warrantyExpires = today + 90;

nicenice Now consider using the STL Now consider using the STL listlist container container

Page 8: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-8 Review: The STL Review: The STL listlist class class

A list object A list object a container class like vector a container class like vector

manages a collection of homogenous objectsmanages a collection of homogenous objects is sequenced--there is a first, second,...,lastis sequenced--there is a first, second,...,last can add objects at the beginning or at the end can add objects at the beginning or at the end

of the list with push_front and push_backof the list with push_front and push_back always knows how big it isalways knows how big it is is generic because it may be declared to store is generic because it may be declared to store

a collection of a collection of anyany class of objects class of objects has useful operations: find, remove, and sorthas useful operations: find, remove, and sort

Page 9: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-9 Construct, Construct, push_backpush_back, , size size

Construct three list objects:Construct three list objects: list <int> tests; list <int> tests; // size is 0// size is 0 list <double> GPAs; list <double> GPAs; list <string> nameslist <string> names; ;

Copy objects into the list with push_back:Copy objects into the list with push_back: tests.tests.push_backpush_back(95); (95); GPAs.push_back(3.67); GPAs.push_back(3.67);

names.push_back("Chris");names.push_back("Chris"); Access the number of objects with size:Access the number of objects with size: cout << tests.cout << tests.sizesize() << endl;() << endl; cout << GPAs.size() << endl;cout << GPAs.size() << endl;

cout << names.size() << endl;cout << names.size() << endl;

Page 10: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-10 Can we store objects we designed?Can we store objects we designed?

The STL list contains int, double, and stringThe STL list contains int, double, and string What about our own objects?What about our own objects?

bankAccount one("Hal", 111.11);bankAccount one("Hal", 111.11); bankAccount two("Sue", 222.22);bankAccount two("Sue", 222.22); bankAccount tre("Deb", 333.33);bankAccount tre("Deb", 333.33); list <bankAccount> acctList;list <bankAccount> acctList; acctList.push_back(one);acctList.push_back(one); acctList.push_back(two);acctList.push_back(two); acctList.push_back(tre);acctList.push_back(tre); acctList.push_back(bankAccount("Four", 4.44));acctList.push_back(bankAccount("Four", 4.44));

Page 11: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-11 STL element requirementsSTL element requirements

The STL containers (list, vector, map) require The STL containers (list, vector, map) require the contained elements to havethe contained elements to have a way to copy elementsa way to copy elements

the container elements are copies of the objects insertedthe container elements are copies of the objects inserted could use the default = operatorcould use the default = operator

a way to compare elementsa way to compare elements could use the relational operators could use the relational operators

< == > != <= >= < == > != <= >=

Page 12: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-12 STL needs all relational STL needs all relational operators definedoperators defined

Any STL container can be sorted when the Any STL container can be sorted when the elements understand less than elements understand less than <<

acctList.sort(); acctList.sort(); // overload < to sort// overload < to sort

Any STL container can be searched when the Any STL container can be searched when the elements understand equal elements understand equal ====

list <bankAccount>::iterator i; list <bankAccount>::iterator i; i = find(acctList.begin(),i = find(acctList.begin(), acctList.end(),acctList.end(), bankAccount("Sue", 0.00));bankAccount("Sue", 0.00));

Other operations require other operators, so Other operations require other operators, so also overload !=, <=, >=, and >also overload !=, <=, >=, and >

Page 13: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-13 Operator functionsOperator functions

Operators functions have a different syntaxOperators functions have a different syntax Some are free functionsSome are free functions

today < tomorrow today < tomorrow // operator < (Date,Date)// operator < (Date,Date)

Some are member functions Some are member functions d += 30; d += 30; // d.operator += (int)// d.operator += (int)

Both need access to private data either Both need access to private data either directly or through an accessing functiondirectly or through an accessing function

Here is a Here is a << free function for bankAccount free function for bankAccount it will use accessing functions to get datait will use accessing functions to get data

Page 14: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-14 The header file The header file bankAccount.hbankAccount.h

class bankAccount {class bankAccount {public:public: // constructors, modifiers, and this accessor// constructors, modifiers, and this accessor string name();string name();private: private: // data members and functions// data members and functions};};

//--auxiliary free functions//--auxiliary free functionsbool operator < ( const bankAccount& left, bool operator < ( const bankAccount& left, const bankAccount& right );const bankAccount& right );bool operator == ( const bankAccount& left,bool operator == ( const bankAccount& left, const bankAccount& right );const bankAccount& right );

Page 15: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-15What does < mean?What does < mean? Answer: anything you wantAnswer: anything you want

The The << and and ==== operators are overloaded for operators are overloaded for bankAccount using this general form:bankAccount using this general form:

bool operatorbool operator an-operator an-operator

( const( const classclass&& left left, const, const classclass&& right right ););

We can give any meaning to less than We can give any meaning to less than << decision: a < b is true when left's name decision: a < b is true when left's name

alphabetically precedes right's namealphabetically precedes right's name

Page 16: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-16 Visualize < betweenVisualize < between the parameters the parameters

// from the file baccount.cpp// from the file baccount.cppbool operator bool operator << (const bankAccount& left, (const bankAccount& left, const bankAccount& right) const bankAccount& right) { { return left.name() return left.name() << right.name(); right.name(); }}

// From a test driver// From a test driverint main() int main() { { bankAccount b1("Bob", 222.00);bankAccount b1("Bob", 222.00); bankAccount b2("Carla", 111.00);bankAccount b2("Carla", 111.00); if(b1 if(b1 << b2) b2) // ...// ...

Page 17: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-17Completing the relational Completing the relational operatorsoperators// from the file baccount.cpp// from the file baccount.cpp

bool operator == (const bankAccount& left,bool operator == (const bankAccount& left, const bankAccount& right) const bankAccount& right) { { return left.name() == right.name(); return left.name() == right.name(); }}

bool operator!= (const bankAccount& lhs,bool operator!= (const bankAccount& lhs, const bankAccount& rhs) const bankAccount& rhs) {{ return lhs.name() != rhs.name(); return lhs.name() != rhs.name(); }}

Page 18: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-18 Complete all 6 for each classComplete all 6 for each class

// from the file baccount.cpp// from the file baccount.cppbool operator > (const bankAccount& lhs, bool operator > (const bankAccount& lhs, const bankAccount& rhs)const bankAccount& rhs){{ return lhs.name() > rhs.name(); return lhs.name() > rhs.name(); }}

bool operator <= (const bankAccount& lhs, bool operator <= (const bankAccount& lhs, const bankAccount& rhs) const bankAccount& rhs) { { return lhs.name() <= rhs.name(); return lhs.name() <= rhs.name(); }}

bool operator >= (const bankAccount& lhs, bool operator >= (const bankAccount& lhs, const bankAccount& rhs) const bankAccount& rhs) { { return lhs.name() >= rhs.name(); return lhs.name() >= rhs.name(); }}

Page 19: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-19 Summing UpSumming Up

Operator overloading allows new classes to look Operator overloading allows new classes to look more like built-in types more like built-in types don't go crazydon't go crazy

C++ operator overloading is sometimes nice, C++ operator overloading is sometimes nice, sometimes necessarysometimes necessary

Operator functions have a different syntaxOperator functions have a different syntax The STL requires all six relational operators The STL requires all six relational operators There is a shortcut described in the standardThere is a shortcut described in the standard

If you define If you define << and and ==== the compiler will define the rest the compiler will define the rest for you for you

Page 20: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-20 Coming UpComing Up

Overloading input and output operatorsOverloading input and output operators Friend functions for efficiencyFriend functions for efficiency Member operator functions Member operator functions +=+=

Page 21: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-21 18.2 Using Friend Functions18.2 Using Friend Functions

The previous member functions call accessor The previous member functions call accessor methods to get the namesmethods to get the names

these two function calls can slow down programsthese two function calls can slow down programs consider sorting a large list of objects, for consider sorting a large list of objects, for

example example each comparison requires 2 function callseach comparison requires 2 function calls

it would be better to access the data members it would be better to access the data members directlydirectly but the data members are privatebut the data members are private

C++ workaround: friend functionsC++ workaround: friend functions

Page 22: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-22 friend functionsfriend functions

functions can be declared inside a class with functions can be declared inside a class with the friend tagthe friend tag

this gives the function access to private data this gives the function access to private data membersmembers

Consider this modification Consider this modification

Page 23: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-23 Not a member function, but Not a member function, but rather a friend functionrather a friend function

class bankAccount {class bankAccount {public:public: //...//... double balance() const;double balance() const; string name() const;string name() const;

//--friend operator functions//--friend operator functions friendfriend bool operator == (const bankAccount& left, bool operator == (const bankAccount& left, const bankAccount& right);const bankAccount& right); friendfriend bool operator < (const bankAccount& left, bool operator < (const bankAccount& left, const bankAccount& right);const bankAccount& right); //...//...};};

Page 24: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-24 Implementing friend functionsImplementing friend functions

Friend functions are free functions Friend functions are free functions They have access to the private data fields of the class They have access to the private data fields of the class

where they were declared where they were declared bool operator == (const bankAccount& left, bool operator == (const bankAccount& left, const bankAccount& right)const bankAccount& right) { { // Reference data members directly// Reference data members directly return left.my_name == right.my_name; return left.my_name == right.my_name; } }

bool operator < (const bankAccount& left, bool operator < (const bankAccount& left, const bankAccount& right)const bankAccount& right) { { // Avoid function-call overhead // Avoid function-call overhead return left.my_name < right.my_name; return left.my_name < right.my_name; }}

Page 25: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-2518.3 Overloading = for Classes 18.3 Overloading = for Classes with Pointer Data Memberswith Pointer Data Members

C++ overrides the = operator for vectorsC++ overrides the = operator for vectors So if a collection class like bag is assigned to So if a collection class like bag is assigned to

another, all vector elements are actually copied from another, all vector elements are actually copied from one to the otherone to the other

// The bag class with a vector data member// The bag class with a vector data member // obtained with a typedef and #include "bag"// obtained with a typedef and #include "bag" bag b1;bag b1; bag b2;bag b2; for(int j = 0; j < 6; j++)for(int j = 0; j < 6; j++) b1.add(j);b1.add(j); b2 = b1;b2 = b1; // b2 is exactly like b1 because vector overloads =// b2 is exactly like b1 because vector overloads =

Page 26: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-26 = with pointers = with pointers

Since the generic class has a pointer, the same Since the generic class has a pointer, the same assignment does not work.assignment does not work.

So if a collection class like bag is assigned to another, So if a collection class like bag is assigned to another, only the pointer is copied only the pointer is copied shallow copyshallow copy

// The bag class with a pointer data member// The bag class with a pointer data member // obtained with #include "genbag"// obtained with #include "genbag" bag b1;bag b1; bag b2;bag b2; for(int j = 0; j < 6; j++)for(int j = 0; j < 6; j++) b1.add(j);b1.add(j); b2 = b1;b2 = b1; // Only the pointer gets copied and the program // Only the pointer gets copied and the program // could terminate prematurely later on. // could terminate prematurely later on.

Page 27: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-27 Overloading = for vectorOverloading = for vector

The bag class should overload =The bag class should overload = The operator = function must copy the The operator = function must copy the

individual objects from one bag to the otherindividual objects from one bag to the other use a for loopuse a for loop

For example, the vector class that comes with For example, the vector class that comes with this book does thatthis book does that

see next slidesee next slide

Page 28: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-28 vector operator =vector operator =

// operator = is defined inside the vector class definition// operator = is defined inside the vector class definitionvector& operator = (const vector<VectorElementType>& right)vector& operator = (const vector<VectorElementType>& right){ { if( this != &right ) if( this != &right ) // Skip deleting when aVec == aVec// Skip deleting when aVec == aVec { { // Deallocate unneeded memory (x is a pointer)// Deallocate unneeded memory (x is a pointer) delete [] x;delete [] x; // Copy the capacity data member// Copy the capacity data member this->my_capacity = right.my_capacity;this->my_capacity = right.my_capacity; // Allocate precisely the correct amount of memory// Allocate precisely the correct amount of memory this->x = new VectorElementType [this->my_capacity]; this->x = new VectorElementType [this->my_capacity]; // Copy the individual items from the right to the left// Copy the individual items from the right to the left for(int j = 0; j < this->my_capacity; j++)for(int j = 0; j < this->my_capacity; j++) {{ this->x[j] = right.x[j];this->x[j] = right.x[j]; }} }} return *this;return *this;}}

Page 29: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-29 How it worksHow it works

First check to make sure you are not assigning First check to make sure you are not assigning the vector to itselfthe vector to itself

this expression is true if the address of the object to this expression is true if the address of the object to the left of = (this) is the same address as the object to the left of = (this) is the same address as the object to the right &rightthe right &right

if( this != &right ) if( this != &right ) // Skip deleting when aVec == aVec// Skip deleting when aVec == aVec

Don't do it. Otherwise the object gets deleted withDon't do it. Otherwise the object gets deleted with delete [] x;delete [] x;

Then copy the value of capacityThen copy the value of capacity Then use a for loop to copy every element Then use a for loop to copy every element

Page 30: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-30 String operator =String operator =

The vector = function finally returns the The vector = function finally returns the address of new vector object address of new vector object vector&vector&

The string operator = function uses the same The string operator = function uses the same algorithmalgorithm

instead of a for loop, string uses the strcpy instead of a for loop, string uses the strcpy function.function.

see next slidesee next slide

Page 31: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-31 String operator =String operator =

string& string::operator = (const string& right)string& string::operator = (const string& right){{ if (this != (&right) )if (this != (&right) ) { { delete [] my_chars; delete [] my_chars; my_len = right.my_len;my_len = right.my_len; my_chars = new char[my_len + 1];my_chars = new char[my_len + 1]; strcpy(my_chars, right.my_chars);strcpy(my_chars, right.my_chars); }} return *this;return *this;}}

Page 32: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-3218.4 Developing the complex 18.4 Developing the complex ClassClass

This complex number class acts as a review for operator overloading

Think of a complex number as one point on the Cartesian (complex) plane.

The point is usually written as (1, 2) where 1 is the number on the real axis (x axis) and 2 is a value on the imaginary axis (y axis).

Page 33: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-33Imaginary AxisImaginary Axis

¦¦

3i +3i +

¦¦ (3.0, 2.0) (3.0, 2.0)

2i + 2i +

(-2.0, 1.0) ¦(-2.0, 1.0) ¦

i +i +

¦ (3.5, 0.0) ¦ (3.5, 0.0)

-+---+---+---+---+---+---+--+---+----+---+---+---+---+---+---+--+---+--- Real AxisReal Axis

-3 -2 1 0¦ 1 2 3 4 5-3 -2 1 0¦ 1 2 3 4 5

-i +-i +

¦(1.5, -2.0)¦(1.5, -2.0)

-2i + -2i +

(-3.0, -3.0) ¦(-3.0, -3.0) ¦

-3i +-3i +

¦¦

Page 34: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-34 Complex numbersComplex numbers

Complex numbers are used a lot in certain fields Complex numbers are used a lot in certain fields electrical engineering for exampleelectrical engineering for example

Standard C++ now has a complex classStandard C++ now has a complex class we'll develop our ownwe'll develop our own

We'll consider a simple app:We'll consider a simple app: find the center of a trianglefind the center of a triangle

defined as the average of the three pointsdefined as the average of the three points sum three complex numbers and divide by threesum three complex numbers and divide by three see next slide see next slide

Page 35: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-35 complex overloads +, /, <<complex overloads +, /, <<

#include <iostream>#include <iostream>using namespace std;using namespace std;#include "ltcomplx" #include "ltcomplx" // author-supplied// author-supplied complex classcomplex classint main()int main(){ { // construct three complex numbers// construct three complex numbers complex a(0, 0);complex a(0, 0); complex b(1, 1);complex b(1, 1); complex c(0.75, 2.15);complex c(0.75, 2.15); complex triangleCenter = (a + b + c) / 3.0;complex triangleCenter = (a + b + c) / 3.0; cout << "\nCenter of triangle (" << a << " + " cout << "\nCenter of triangle (" << a << " + " << b << " + " << c << ") / 3 is " << endl;<< b << " + " << c << ") / 3 is " << endl; cout << triangleCenter << endl;cout << triangleCenter << endl;}}

OutputOutputCenter of triangle ((0, 0) + (1, 1) + (0.75, 2.15)) / 3 isCenter of triangle ((0, 0) + (1, 1) + (0.75, 2.15)) / 3 is(0.583333, 1.05)(0.583333, 1.05)

Page 36: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-36 18.4.2 Design18.4.2 Design

Want the complex class to handle complex Want the complex class to handle complex arithmetic as easily as real arithmetic with int arithmetic as easily as real arithmetic with int and doubleand double

like to have + - / * like to have + - / * like to allow input and outputlike to allow input and output there are a host of other complex function such as there are a host of other complex function such as

abs and sqrt abs and sqrt don't want programmers to have to remember and don't want programmers to have to remember and

perform complex multiplication and divisionperform complex multiplication and division

Page 37: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-37 18.4.3 Implementation18.4.3 Implementation

Each complex number has a real part and an Each complex number has a real part and an imaginary partimaginary part

two doubles called my_real and my_imag could two doubles called my_real and my_imag could store the state of a complex objectstore the state of a complex object

We could have several constructorsWe could have several constructors default, one argument and 2 arguments to allowdefault, one argument and 2 arguments to allow

complex a;complex a; complex b( -1.0 ); complex b( -1.0 ); // the real number -1.0// the real number -1.0 complex b( 12.57, 1.99 );complex b( 12.57, 1.99 );

Page 38: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-38Also overload some operators Also overload some operators as friend functionsas friend functions

class complex {class complex {public:public://--constructors//--constructors complex();complex(); // complex a;// complex a; complex(double initReal) complex(double initReal) // complex b(1.0);// complex b(1.0); complex(double initReal, complex(double initReal, // complex c(1.0. 2.0);// complex c(1.0. 2.0); double initImag); double initImag);

//--accessors//--accessors double real();double real(); double imag();double imag();

//--operator functions//--operator functions friend complex operator + (complex left, complex right);friend complex operator + (complex left, complex right); friend complex operator / (complex left, complex right);friend complex operator / (complex left, complex right); friend ostream& operator << (ostream& os, complex right);friend ostream& operator << (ostream& os, complex right); friend istream& operator >> (istream& is, complex& right);friend istream& operator >> (istream& is, complex& right);

private:private: double my_real;double my_real; double my_imag;double my_imag;};};

Page 39: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-39 Overloading +Overloading +

complex operator + (complex left, complex right)complex operator + (complex left, complex right){ { // Complex addition // Complex addition // (a + bi) + (c + di) = (a + c) + (b + d)i // (a + bi) + (c + di) = (a + c) + (b + d)i

// a + c, the real part// a + c, the real part double tempReal = left.my_real + right.my_real; double tempReal = left.my_real + right.my_real;

// b + d, imaginary part// b + d, imaginary part double tempImag = left.my_imag + right.my_imag; double tempImag = left.my_imag + right.my_imag;

// Construct a complex object and return it// Construct a complex object and return it complex temp(tempReal, tempImag); complex temp(tempReal, tempImag); return temp; return temp; }}

Page 40: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-40 Overloading << Overloading <<

The input and output operators can be The input and output operators can be overloaded for any new classoverloaded for any new class

in fact, the C++ system does this for all the in fact, the C++ system does this for all the standard typesstandard types

What has to be done:What has to be done: Make operator << it a friend for efficiencyMake operator << it a friend for efficiency take an ostream& parameter in addition to the take an ostream& parameter in addition to the

complex argumentcomplex argument return a reference to the changed ostreamreturn a reference to the changed ostream

Page 41: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-41 operator <<operator <<

The left operator is an ostream object, cout for The left operator is an ostream object, cout for instance, the complex object is the rightinstance, the complex object is the right

cout << complex( 1.2, 3.4 ) << endl;cout << complex( 1.2, 3.4 ) << endl;

The return type is needed to allow chaining The return type is needed to allow chaining output together like thisoutput together like this

complex a, b, c;complex a, b, c; cout << a << b << c;cout << a << b << c;

cout << a returns the ostream you are cout << a returns the ostream you are outputting to so cout << b can occur nextoutputting to so cout << b can occur next

Page 42: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-42 output it as you pleaseoutput it as you pleaseuse ( , and )use ( , and )

Here is the function heading as from ltcomplex.hHere is the function heading as from ltcomplex.h //--operator function//--operator function friend ostream& operator << (ostream& os, friend ostream& operator << (ostream& os, complex right);complex right);

Its implementationIts implementation ostream& operator << (ostream& os, complex right)ostream& operator << (ostream& os, complex right) {{ left << "(" << right.my_real << ", "left << "(" << right.my_real << ", " << right.my_imag << ")";<< right.my_imag << ")";

returnreturn os;os; }}

Page 43: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-43 Complex number outputComplex number output

OutputOutput complex a(0.75, 2.15);complex a(0.75, 2.15); complex b(-1.5, 0.5);complex b(-1.5, 0.5); cout << a << " " << b << endl;cout << a << " " << b << endl;

OutputOutput (0.75, 2.15) (-1.5, 0.5)(0.75, 2.15) (-1.5, 0.5)

Page 44: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-4418.4.7 Overloading >> for 18.4.7 Overloading >> for complex inputcomplex input

You can also input a complex number as two You can also input a complex number as two numbers in a rownumbers in a row

must overload >>must overload >> make it a friend function for efficiencymake it a friend function for efficiency need the left argument to be an istream object, cin need the left argument to be an istream object, cin

for examplefor example need a complex reference parameter need a complex reference parameter it must changeit must change return a reference to an ostream object to allow return a reference to an ostream object to allow

chaining of input like thischaining of input like this complex a, b, c;complex a, b, c; cin >> a >> b >> c;cin >> a >> b >> c;

Page 45: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-45 input as you pleaseinput as you pleasethis just reads two numbersthis just reads two numbers

Here is the function heading as from ltcomplex.hHere is the function heading as from ltcomplex.h //--operator function//--operator function friend istream& operator >> (istream& is, friend istream& operator >> (istream& is, complex right);complex right);

Its implementationIts implementation istream& operator >> (istream& left, complex& right) istream& operator >> (istream& left, complex& right) { { double x, y; double x, y; // Get two numbers from the input stream is == cin// Get two numbers from the input stream is == cin is >> x >> y; is >> x >> y; // is is the same as cin// is is the same as cin // Now modify the right argument (c1)// Now modify the right argument (c1) right = complex(x, y); right = complex(x, y); return is; return is; };

Page 46: 18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

18-46 Complex number outputComplex number output

OutputOutput complex a(0.75, 2.15);complex a(0.75, 2.15); complex b(-1.5, 0.5);complex b(-1.5, 0.5); cout << a << " " << b << endl;cout << a << " " << b << endl;

OutputOutput (0.75, 2.15) (-1.5, 0.5)(0.75, 2.15) (-1.5, 0.5)