Upload
others
View
19
Download
0
Embed Size (px)
Citation preview
Ch 8. Operator Overloading, Friends, and References
2013-2 O-O Programming & Data Structure
September 4, 2013
Prof. Young-Tak Kim Advanced Networking Technology Lab. (YU-ANTL)
Dept. of Information & Comm. Eng, Graduate School, Yeungnam University, KOREA
(Tel : +82-53-810-2497; Fax : +82-53-810-4742 http://antl.yu.ac.kr/; E-mail : [email protected])
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 2
Outline
Basic Operator Overloading Unary operators: ++, -- Binary operators: +, -, *, /, %, ==, != As member functions
Friends and Automatic Type Conversion Friend functions, friend classes Constructors for automatic type conversion
References and More Overloading << and >> Operators: = , [], ++, --
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 3
Operator Overloading Introduction Operators +, -, %, ==, etc. Really just functions!
Simply "called" with different syntax: x + 7 "+" is binary operator with x and 7 as operands We "like" this notation as humans
Think of it as: +(x, 7) "+" is the function name x, 7 are the arguments Function "+" returns "sum" of it’s arguments
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 4
Operator Overloading Perspective Built-in operators e.g., +, -, = , %, ==, /, * Already work for C++ built-in types In standard "binary" notation
We can overload them! To work with OUR types! To add "Chair types", or "Money types" As appropriate for our needs In "notation" we’re comfortable with
Always overload with “similar actions"!
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 5
Why Operator Overloading is necessary ?
Concise expression and easy to understand using the usual mathematical operators, concise notations are
possible /* What you have use */
double mA[N][N], mB[N][N], mC[N][N], mD[N][N], mE[N][N], mF[N][N]; getMtrx(mA, N); getMtrx(mB, N); mtrxAdd(mA, mB, mC, N); mtrxSubtract(mA, mB, mD, N); mtrxMultiply(mA, mB, mE, N); mtrxInverse(mA, mF, N);
/* What can be possible with */ // Class definition for Mtrx Mtrx mA, mB, mC, mD, mE, mInv; cin >> mA; cin >> mB; mC = mA + mB; mD = mA - mB; mE = mA * mB; mInv = ~mA;
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 6
Overloading Basics
Overloading operators VERY similar to overloading functions Operator itself is "name" of function
Example Declaration: const Money operator +( const Money& amount1, const Money& amount2);
Overloads + for operands of type Money Uses constant reference parameters for efficiency Returned value is type Money Allows addition of "Money" objects
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 7
Implementation of operator overloading
Two approaches case 1: implementation as non-member function similar to usual function overloading standalone function operator overloading is not included in class definition generally simple to implement
case 2: implementation as a member function operator overloading is included in class definition principles suggest member operators, to maintain the “sprit” of object-
oriented programming
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 8
Overloaded "+"
Given previous example: Note: overloaded "+" NOT member function Definition is "more involved" than simple "add" Requires issues of money type addition Must handle negative/positive values
Operator overload definitions generally very simple Just perform "addition" particular to "your" type
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 9
Money "+" Definition Definition of "+" operator for Money class:
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 10
Overloaded "=="
Equality operator, == Enables comparison of Money objects Declaration:
bool operator ==(const Money& amount1, const Money& amount2); Returns bool type for true/false equality
Again, it’s a non-member function (like "+" overload)
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 11
Overloaded "==" for Money Definition of "==" operator for Money
class:
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 12
Constructors Returning Objects
Constructor a "void" function? We "think" that way, but no A "special" function With special properties CAN return a value!
Recall return statement in "+" overload for Money type: return Money(finalDollars, finalCents); Returns an "invocation" of Money class! So constructor actually "returns" an object! Called an "anonymous object"
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 13
Returning by const Value
Consider "+" operator overload again: const Money operator +(const Money& amount1, const Money& amount2); Returns a "constant object"? Why?
Consider impact of returning "non-const" object to see…
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 14
Returning by non-const Value
Consider "no const" in declaration: Money operator +(const Money& amount1, const Money& amount2);
Consider expression that calls: m1 + m2 Where m1 & m2 are Money objects Object returned is Money object We can "do things" with objects! Like call member functions…
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 15
What to do with Non-const Object
Can call member functions: We could invoke member functions on
object returned by expression m1+m2: (m1+m2).output(); //Legal, right?
– Not a problem: doesn’t change anything
(m1+m2).input(); //Legal! – PROBLEM! //Legal, but MODIFIES! Allows modification of "anonymous" object! Can’t allow that here!
So we define the return object as const
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 16
Overloading Unary Operators
C++ has unary operators: Defined as taking one operand e.g., - (negation) x = -y; // Sets x equal to negative of y
Other unary operators: ++ (increment), -- (decrement)
Unary operators can also be overloaded
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 17
Overload "-" for Money
Overloaded "-" function declaration Placed outside class definition:
const Money operator –(const Money& amount); Notice: only one argument Since only 1 operand (unary)
"-" operator is overloaded twice! For two operands/arguments (binary) For one operand/argument (unary) Definitions must exist for both
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 18
Overloaded "-" Definition
Overloaded "-" unary function definition: const Money operator –(const Money& amount) { return Money(-amount.getDollars(), -amount.getCents()); }
Applies "-" unary operator to built-in type Operation is "known" for built-in types
Returns anonymous object again
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 19
Overloaded "-" Usage
Consider: Money amount1(10), amount2(6), amount3; amount3 = amount1 – amount2; Calls binary "-" overload
amount3.output(); //Displays $4.00 amount3 = -amount1; Calls unary "-" overload
amount3.output(); //Displays -$10.00
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 20
Overloading as Member Functions Previous examples: standalone functions Defined outside a class
Can overload as "member operator" Considered "member function" like others
When operator is member function: Only ONE parameter, not two! Calling object serves as 1st parameter
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 21
Member Operator in Action
Money cost(1, 50), tax(0, 15), total; total = cost + tax; If "+" overloaded as member operator: Variable/object cost is calling object Object tax is single argument
Think of as: total = cost+(tax);
Declaration of "+" in class definition: const Money operator+(const Money& amount); Notice only ONE argument
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 22
Example Cmplx (1)
/** * Cmplx.h */ #include <iostream> using namespace std; class Cmplx { friend ostream & operator<< (ostream &, const Cmplx &); friend istream & operator>> (istream &, Cmplx &); public: Cmplx(double real=0.0, double imagin=0.0); // constructor const Cmplx operator+(const Cmplx &); const Cmplx operator-(const Cmplx &); private: double real; double imagin; };
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 23
Example Cmplx (2) /** * Cmplx.cpp */ #include <iostream> #include "Cmplx.h" using namespace std; Cmplx::Cmplx(double r, double i) :real(r), imagin(i) { } ostream &operator<<(ostream &output, const Cmplx &c) { output << "Complex (" << c.real << ", " << c.imagin << ")" << endl; return output; } istream &operator>>(istream &input, Cmplx &c) { input >> c.real; input >> c.imagin; return input; }
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 24
Example Cmplx (3)
/* Cmplx.cpp (cont.) */ const Cmplx Cmplx::operator+(const Cmplx &c) { Cmplx result; result.real = real + c.real; result.imagin = imagin + c.imagin; return result; } const Cmplx Cmplx::operator-(const Cmplx &c) { Cmplx result; result.real = real - c.real; result.imagin = imagin - c.imagin; return result; }
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 25
Example Cmplx (4) /**
* main.cpp */ #include <iostream> #include "Cmplx.h" using namespace std; void main() { Cmplx c1, c2, c3, c4; cout << "input c1.real and c1.imagin: "; cin >> c1; cout << "c1 : " << c1 << endl; cout << "input c2.real and c2.imagin: "; cin >> c2; cout << "c2 : " << c2 << endl; c3 = c1 + c2; cout << "c3 = c1 + c2: " << c3 << endl; c4 = c1 - c2; cout << "c4 = c1 - c2: " << c4 << endl; }
<Result of Execution>
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 26
const Functions
When to make function const? Constant functions not allowed to alter class
member data Constant objects can ONLY call constant
member functions
Good style dictates: Any member function that will NOT modify data
should be made const
Use keyword const after function declaration and heading
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 27
Overloading Operators: Which Method?
Object-Oriented-Programming Principles suggest member operators Many agree, to maintain "spirit" of OOP
Member operators more efficient No need to call accessor (e.g., get()) and mutator (e.g., set())
functions
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 28
Overloading Function Application () Function call operator, ( ) Must be overloaded as member function Allows use of class object like a function Can overload for all possible numbers of arguments
Example: Aclass anObject; anObject(42); If ( ) overloaded calls overload
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 29
Other Overloads
&&, ||, and comma (‘,’) operator Predefined versions work for bool types Recall: use "short-circuit evaluation" When overloaded no longer uses short-circuit Uses "complete evaluation" instead Contrary to expectations
Generally should not overload these operators
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 30
Friend Functions
Nonmember functions Recall: operator overloads as nonmembers They access data through accessor and mutator functions Very inefficient (overhead of calls)
Friends can directly access private class data No overhead, more efficient
So: best to make nonmember operator overloads friends!
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 31
Friend Functions
Friend function of a class Not a member function Has direct access to private members Just as member functions do
Use keyword friend in front of function declaration Specified IN class definition But they’re NOT member functions!
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 32
Friend Function Uses
Operator Overloads Most common use of friends Improves efficiency Avoids need to call accessor/mutator member functions Operator must have access anyway Might as well give full access as friend
Friends can be any function
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 33
Example of friend function (1)
/** * Cmplx.h */ #include <iostream> using namespace std; class Cmplx { friend ostream & operator<< (ostream &, const Cmplx &); friend istream & operator>> (istream &, Cmplx &); public: Cmplx(double real=0.0, double imagin=0.0); // constructor const Cmplx operator+(const Cmplx &); const Cmplx operator-(const Cmplx &); private: double real; double imagin; };
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 34
Example of friend function (2) /* Cmplx.cpp */ ostream &operator<<(ostream &output, const Cmplx &c) { output << "Complex (" << c.real << ", " << c.imagin << ")" << endl; return output; } istream &operator>>(istream &input, Cmplx &c) { input >> c.real; input >> c.imagin; return input; }
/** main.cpp */ . . . . Cmplx c1, c2, c3, c4; cout << " input c1.real and c1.imagin: "; cin >> c1; cout << " c1 : " << c1 << endl; cout << " input c2.real and c2.imagin: "; cin >> c2; cout << " c2 : " << c2 << endl; . . . .
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 35
Friend Function Purity
Friends not pure? "Spirit" of OOP dictates all operators and functions be
member functions Many believe friends violate basic OOP principles
Advantageous? For operators: very! Allows automatic type conversion Still encapsulates: friend is in class definition Improves efficiency
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 36
Friend Classes
Entire classes can be friends Similar to function being friend to class Example:
class F is friend of class C All class F member functions are friends of C NOT reciprocated Friendship granted, not taken
Syntax: friend class F Goes inside class definition of "authorizing" class
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 37
References
Reference defined: Name of a storage location Similar to "pointer"
Example of stand alone reference: int robert;
int& bob = robert; bob is reference to storage location for robert Changes made to bob will affect robert
Confusing?
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 38
Comparisons of call-by-{value, reference, pointer}
Call-by-Value
/* Call-by-Value */ int function( int x ) { int y; y = x * x + 2; return y; } void main() { int j, k; . . . . k = function ( j ); }
Call-by-Reference
/* Call-by-Reference */ int function( int& x ) { int y; y = x * x + 2; return y; } void main() { int j, k; . . . . k = function ( j ); }
Call-by-Pointer
/* Call-by-Reference */ int function( int* px ) { int y; y = (*px) * (*px) + 2; retrun y; } void main() { int j, k; . . . . k = function ( &j ); }
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 39
References Usage
Seemingly dangerous
Useful in several cases:
Call-by-reference Often used to implement this mechanism
Returning a reference Allows operator overload implementations to
be written more naturally Think of as returning an "alias" to a variable
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 40
Returning Reference
Syntax: double& sampleFunction(double& variable); double& and double are different Must match in function declaration and heading
Returned item must "have" a reference Like a variable of that type Cannot be expression like "x+5" Has no place in memory to "refer to"
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 41
Returning Reference in Definition
Example function definition: double& sampleFunction(double& variable) { return variable; }
Trivial, useless example Shows concept only Major use: Certain overloaded operators, such as extraction operator (>>)
and insertion operator (<<)
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 42
Overloading >> and <<
Enables input and output of our objects Similar to other operator overloads New subtleties
Improves readability Like all operator overloads do Enables:
cout << myObject; cin >> myObject;
Instead of need for: myObject.output(); myObject.input(); …
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 43
Overloading <<
Insertion operator, << Used with cout A binary operator
Example: cout << "Hello"; Operator is << 1st operand is predefined object cout From library iostream
2nd operand is literal string "Hello"
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 44
Overloading <<
Operands of << Cout object, of class type ostream Our class type
Recall Money class Used member function output() Nicer if we can use << operator:
Money amount(100); cout << "I have " << amount << endl;
instead of: cout << "I have "; amount.output()
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 45
Overloaded << Return Value
Money amount(100); cout << amount; << should return some value To allow cascades:
cout << "I have " << amount; (cout << "I have ") << amount; Two are equivalent
What to return? cout object! Returns its first argument type, ostream
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 46
Overloaded << and >> Example:
Display 8.5 Overloading << and >> (1 of 5)
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 47
Display 8.5 Overloading << and >> (2 of 5)
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 48
Display 8.5 Overloading << and >> (3 of 5)
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 49
Display 8.5 Overloading << and >> (4 of 5)
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 50
Display 8.5 Overloading << and >> (5 of 5)
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 51
Assignment Operator, =
Must be overloaded as member operator Automatically overloaded Default assignment operator: Member-wise copy Member variables from one object
corresponding member variables from other
Default OK for simple classes But class with pointers and dynamic memory allocation must write our own assignment operator= overloading!
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 52
Example of “operator=” overloading (1) /** Date.h */ #include <iostream> using namespace std; class DateArray; class Date { friend class DateArray; friend istream &operator>>(istream &, Date &); friend ostream &operator<<(ostream &, const Date &); public: Date(); Date(int y, int m, int d); const Date operator+(int dd); const Date operator-(int dd); const Date operator++(); // prefix const Date operator++(int dummy); // postfix const Date operator--(); // prefix const Date operator--(int dummy); // postfix const Date operator=(const Date rightSide); private: int year; int month; int day; };
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 53
Example of “operator=” overloading (2)
const Date Date::operator=(const Date rightSide) { year = rightSide.year; if (rightSide.month >=1 && rightSide.month <=12) { month = rightSide.month; } else { cout << "Error in month assignment : " << rightSide.month << endl; month = 1; } if (rightSide.day >= 1 && rightSide.day <= daysPerMonth[month]) { day = rightSide.day; } else { cout << "Error in day assignment : " << rightSide.day; cout << " ( month: " << rightSide.month << ")" << endl; day = 1; } return *this; }
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 54
Increment and Decrement
Each operator has two versions Prefix notation: ++x; y = ++x; same as x = x+1; y = x;
Postfix notation: x++; y = x++; same as y = x; x = x+1
Must distinguish in overload Standard overload method Prefix int operator++();
Add 2d parameter of type int Postfix int operator++(int ignore); Just a marker for compiler! Specifies postfix is allowed
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 55
Display 8.6 (1)
#include <iostream> #include <cstdlib> using namespace std; class IntPair { public: IntPair(int firstValue, int secondValue); IntPair operator++( ); //Prefix version IntPair operator++(int); //Postfix version void setFirst(int newValue); void setSecond(int newValue); int getFirst( ) const; int getSecond( ) const; private: int first; int second; };
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 56
Display 8.6 (2)
int main( ) { IntPair a(1,2); cout << "Postfix a++: Start value of object a: "; cout << a.getFirst( ) << " " << a.getSecond( ) << endl; IntPair b = a++; cout << "Value returned: "; cout << b.getFirst( ) << " " << b.getSecond( ) << endl; cout << "Changed object: "; cout << a.getFirst( ) << " " << a.getSecond( ) << endl; a = IntPair(1, 2); cout << "Prefix ++a: Start value of object a: "; cout << a.getFirst( ) << " " << a.getSecond( ) << endl; IntPair c = ++a; cout << "Value returned: "; cout << c.getFirst( ) << " " << c.getSecond( ) << endl; cout << "Changed object: "; cout << a.getFirst( ) << " " << a.getSecond( ) << endl; return 0; }
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 57
Display 8.6 (3)
IntPair::IntPair(int firstValue, int secondValue) : first(firstValue), second(secondValue) {/*Body intentionally empty*/} IntPair IntPair::operator++(int ignoreMe) //postfix version { int temp1 = first; int temp2 = second; first++; second++; return IntPair(temp1, temp2); } IntPair IntPair::operator++( ) //prefix version { first++; second++; return IntPair(first, second); }
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 58
Display 8.6 (4)
Result of execution see Page 381
void IntPair::setFirst(int newValue) { first = newValue; } void IntPair::setSecond(int newValue) { second = newValue; } int IntPair::getFirst( ) const { return first; } int IntPair::getSecond( ) const { return second; }
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 59
Overload Indexed Array Operator, [ ]
Can overload [ ] for your class To be used with objects of your class
Operator must return a reference!
operator[] must be a member function!
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 60
Example : CmplxArray (1) /** Cmplx.h */ #ifndef CMPLX_H #define CMPLX_H #include <iostream> using namespace std; class CmplxArray; class Cmplx { friend ostream & operator<< (ostream &, const Cmplx &); friend istream & operator>> (istream &, Cmplx &); friend class CmplxArray; public: Cmplx(double real=0.0, double imagin=0.0); // constructor const Cmplx operator+(const Cmplx &); const Cmplx operator-(const Cmplx &); void setReal(double r); void setImagin(double im); private: double real; double imagin; }; #endif
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 61
Example : CmplxArray (2) /** CmplxArray.h */
#ifndef CMPLXARRAY_H #define CMPLXARRAY_H #include <iostream> #include "Cmplx.h" using namespace std; class CmplxArray { public: CmplxArray(int size); // constructor CmplxArray(const CmplxArray &obj); ~CmplxArray(); int size() { return cmplxArrySize; } Cmplx &operator[](int sub); private: Cmplx *pCA; int cmplxArrySize; void subError(); // out of subscript range }; #endif
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 62
Example : CmplxArray (3) /** Cmplx.cpp */
#include <iostream> #include "Cmplx.h" using namespace std; Cmplx::Cmplx(double r, double i) :real(r), imagin(i) { } ostream &operator<<(ostream &output, const Cmplx &c) { output << "Complex (" << c.real << ", " << c.imagin << ")" << endl; return output; } istream &operator>>(istream &input, Cmplx &c) { input >> c.real; input >> c.imagin; return input; }
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 63
Example : CmplxArray (4) void Cmplx::setReal(double r)
{ real = r; } void Cmplx::setImagin(double im) { imagin = im; } const Cmplx Cmplx::operator+(const Cmplx &c) { Cmplx result; result.real = real + c.real; result.imagin = imagin + c.imagin; return result; } const Cmplx Cmplx::operator-(const Cmplx &c) { Cmplx result; result.real = real - c.real; result.imagin = imagin - c.imagin; return result; }
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 64
Example : CmplxArray (5) /** CmplxArray.cpp */
#include "CmplxArray.h" #include "Cmplx.h" CmplxArray::CmplxArray(int size) // constructor { cmplxArrySize = size; pCA = new Cmplx[size]; for (int i=0; i<size; i++) { pCA[i].real = 0.0; pCA[i].imagin = 0.0; } } CmplxArray::CmplxArray(const CmplxArray &obj) // constructor { cmplxArrySize = obj.cmplxArrySize; pCA = new Cmplx[cmplxArrySize]; for (int i=0; i<cmplxArrySize; i++) { pCA[i] = obj.pCA[i]; // *(pCA+i) = obj.pCA[i]; } } CmplxArray::~CmplxArray() // destructor { if (cmplxArrySize > 0) delete [] pCA; }
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 65
Example : CmplxArray (6)
void CmplxArray::subError() { cout << "ERROR: Subscript out of range.\ n"; exit(0); } Cmplx &CmplxArray::operator [](int sub) { if (sub < 0 || sub >= cmplxArrySize) // checking validity of range subError(); return pCA[sub]; }
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 66
Example : CmplxArray (7) #include <iostream>
#include "CmplxArray.h" #include "Cmplx.h" using namespace std; void main() { CmplxArray CMPLXES(4); cout << "\ n Input real and imagin in double type: "; cin >> CMPLXES[0]; cout << " CMPLXES[0] : " << CMPLXES[0] << endl; cout << " Input real and imagin in double type: "; cin >> CMPLXES[1]; cout << " CMPLXES[1] : " << CMPLXES[1] << endl; CMPLXES[2] = CMPLXES[0] + CMPLXES[1]; CMPLXES[3] = CMPLXES[0] - CMPLXES[1]; cout << " CMPLXES[2] : " << CMPLXES[2] << endl; cout << " CMPLXES[3] : " << CMPLXES[3] << endl; }
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 67
Summary 8-1
C++ built-in operators can be overloaded To work with objects of your class
Operators are really just functions
Friend functions have direct private member access
Operators can be overloaded as member functions 1st operand is calling object
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 68
Summary 8-2
Friend functions add efficiency only Not required if sufficient accessors/mutators
available
Reference "names" a variable with an alias
Can overload <<, >> Return type is a reference to stream type
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 69
Homework 8
8.1 Programming projects 8-1. (operator overloading for Class Money)
8.2 Programming projects 8-3. (operator overloading for complex number)
8.3 Operator overloading for Class Mtrx 1)Define a class Mtrx that contains a private data member of 2-dimentional array to
store double data type. Class Mtrx has operator overloading of input/output operator (>>, <<), arithmetic operator (+, -, *), equality operator (==, !=), assignment operator (=).
2)Define a class MtrxArray, that include a given number of Mtrx instances. The MtrxArray should provide operator overloading of [].
3) In main() function, specify 6 instances of 7x7 Mtrx array as mtrx[0..5]. 4) Using 2 two dimensional arrays in the main() function, initialize the first two arrays. 5) Using the mtrx[0] and mtrx[1], perform arithmetic operations (+, -, *), and store
the results at mtrx[2], mtrx[3], and mtrx[4], respectively. 6) Using the mtrx[0] and mtrx[1], perform operators == and !=, print out the results. 7) Output the calculated result of mtrx[] using operator <<. (Note. Header file and main() function should include following sample source code.)
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 70
8.3 (cont) Header File (“Mtrx.h”)
/** Class_Mtrx.h */ #ifndef CLASS_MTRX_H #define CLASS_MTRX_H using namespace std; class Mtrx { friend ostream & operator<< (ostream &, const Mtrx &); friend istream & operator>> (istream &, Mtrx &); public: Mtrx(); Mtrx(int mSize); void init(double dA[], int num_data, int mSize); void init(int mSize); void print(); Mtrx add(Mtrx); Mtrx sub(Mtrx); Mtrx multiply(Mtrx);
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 71
8.3 (cont) Header File (“Mtrx.h”)
/** Class_Mtrx.h (cont.) */ Mtrx operator+(Mtrx); Mtrx operator-(Mtrx); Mtrx operator*(Mtrx); bool operator==(Mtrx); bool operator!=(Mtrx); const Mtrx operator= (const Mtrx &right); private: int mSize; double **dM; double det; }; #endif
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 72
8.3 (cont) Header File (“MtrxArray.h”) /** MtrxArray.h */
#ifndef MTRXARRAY_H #define MTRXARRAY_H #include <iostream> using namespace std; class Mtrx; class MtrxArray { public: MtrxArray(int arraySize, int mtrxSize); Mtrx &operator[](int sub); int getSize(); private: Mtrx *pMtrx; int mtrxArrySize; void subError(); }; #endif
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 73
8.3 (cont) main.cpp
/** main.cpp */ #include <iostream> #include "Mtrx.h" #include "MtrxArray.h" #define MTRX_SIZE 7 #define NUM_MTRX 6 using namespace std; int main() { double mA[MTRX_SIZE * MTRX_SIZE] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 2.0, 3.0, 4.0, 5.0, 1.0, 9.0, 3.0, 3.0, 2.0, 5.0, 3.0, 2.0, 3.0, 2.0, 4.0, 3.0, 2.0, 7.0, 2.0, 7.0, 2.0, 5.0, 3.0, 2.0, 7.0, 2.0, 7.0, 2.0, 6.0, 3.0, 2.0, 7.0, 2.0, 1.0, 5.0, 7.0, 4.0, 3.0, 2.0, 9.0, 5.0, 8.0};
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 74
8.3 (cont) main.cpp
double mB[MTRX_SIZE * MTRX_SIZE] = {1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0}; MtrxArray mtrx(NUM_MTRX, MTRX_SIZE); mtrx[0].init(mA, MTRX_SIZE * MTRX_SIZE, MTRX_SIZE); mtrx[1].init(mB, MTRX_SIZE * MTRX_SIZE, MTRX_SIZE); cout << "mtrx[0]:\ n" << mtrx[0] << endl; cout << "det of mtrx[0]= " << !mtrx[0] << endl; cout << "mtrx[1]:\ n" << mtrx[1] << endl; mtrx[2] = mtrx[0] + mtrx[1]; cout << "mtrx[2] = mtrx[0] + mtrx[1]: \ n" << mtrx[2];
Advanced Networking Tech. Lab. Yeungnam University (YU-ANTL)
O-O Programming & Data Structure Prof. Young-Tak Kim ch 8 - 75
8.3 (cont) main.cpp
mtrx[3] = mtrx[0] - mtrx[1]; cout << "mtrx[3] = mtrx[0] - mtrx[1]: \ n" << mtrx[3]; mtrx[5] = mtrx[0] * mtrx[4]; cout << "mtrx[5] = mtrx[0] * mtrx[4]: \ n" << mtrx[5]; if (mtrx[0] == mtrx[1]) cout << "mtrx[0] and mtrx[1] are equal.\ n"; if (mtrx[0] != mtrx[1]) cout << "mtrx[0] and mtrx[1] are not equal.\ n"; return 0; }