Upload
tavion-ruskin
View
297
Download
2
Tags:
Embed Size (px)
Citation preview
Chapter 11 Chapter 11 Operator Overloading; String Operator Overloading; String and Array Objects and Array Objects Part I
ObjectivesObjectivesFundamentals of Operator
OverloadingRestrictions on Operator
OverloadingOperator Functions as Class
Members vs. Global FunctionsOverloading Stream Insertion and
Stream Extraction OperatorsOverloading Unary OperatorsOverloading Binary Operators
11.1 Introduction11.1 IntroductionUse operators with objects
(operator overloading)◦Clearer than function calls for certain
classes◦Examples◦+
Performs arithmetic on multiple items (like matrix, polynomial, etc.)
4
11.2 Fundamentals of Operator 11.2 Fundamentals of Operator OverloadingOverloadingTypes for operator overloading
◦Can use existing operators with user-defined types Cannot create new operators
Overloading operators◦Create a function for the class◦Name of operator function
Keyword operator followed by symbol Example
operator+ for the addition operator +
Software Engineering Observation Software Engineering Observation 11.111.1
Operator overloading contributes to C++’s extensibility—one of the language’s most appealing attributes.
Good Programming Practice 11.2Good Programming Practice 11.2
Overloaded operators should mimic the built-in functionality
For example, the + operator should be overloaded to perform addition, not subtraction.
11.2 Fundamentals of Operator 11.2 Fundamentals of Operator Overloading Overloading
Overloading provides concise notation◦object2 = object1.add( object2 );
vs.
object2 = object2 + object1;If you want to use operators on a
class object, the operators must be overloaded for that class, except
Assignment operator (=) Memberwise assignment between objects
Address operator (&) Returns address of object
Comma operator (,) Evaluates expression to its left then the expression to
its right
11.3 Restrictions on Operator 11.3 Restrictions on Operator OverloadingOverloading
Cannot change◦ Precedence of operator◦ Associativity (left-to-right or right-to-left)◦ Number of operands
e.g., & is unary, can only act on one operand◦ How operators act on built-in data types (i.e., cannot
change integer addition)Cannot create new operatorsOperators must be overloaded explicitly.
◦ Overloading + and = does not overload +=.Some operators cannot be overloaded.
Fig. 11.1Fig. 11.1 | Operators that can be overloaded. | Operators that can be overloaded.
Operators that can be overloaded
+ - * / % ^ & | ~ ! = < > += -= *=
/= %= ^= &= |= << >> >>=
<<= == != <= >= && || ++
-- ->* , -> [] () new delete
new[] delete[]
Fig. 11.2Fig. 11.2 | Operators that cannot be overloaded. | Operators that cannot be overloaded.
Operators that cannot be overloaded
. .* :: ?:
11.4 Operator Functions as Class 11.4 Operator Functions as Class Members vs. Global MembersMembers vs. Global MembersAs member functions
◦Use this keyword to implicitly get left operand argument
◦Operators (), [], -> or any assignment operator must be overloaded as a class member function
Example – Overlaoding Example – Overlaoding Operator as a Member Operator as a Member FunctionFunctionOverloading operator+ as member
function◦Prototype in the header file (.h): class Complex
{ public: Complex(int=0, int=0); Complex operator+ (Complex); private: int real, imginary; };
Example – Overlaoding Example – Overlaoding Operator as a Member Operator as a Member FunctionFunction
Overloading operator+ as member function◦In main()Complex P, Q;… //Initialize P and QComplex R = P + Q;
Example – Overlaoding Example – Overlaoding Operator as a Member Operator as a Member FunctionFunctionDefinition in the source file (.cpp):
Use this pointer to explicitly indicate the first object operand.
Complex Complex ::operator+(Complex Q){ return Complex(real+Q.real, imaginary+Q.imaginary);}
Complex Complex ::operator+(Complex Q){ return Complex(this->real+Q.real, this->imaginary+Q.imaginary);}
11.4 Operator Functions as Class 11.4 Operator Functions as Class Members vs. Global MembersMembers vs. Global MembersAs global functions
◦Need parameters for both operands◦Can be a friend to access private or protected data
Example – Overlaoding Example – Overlaoding Operator as a Global FunctionOperator as a Global FunctionOverloading operator+ as global
function ◦Prototype:
operator+() is not part of class Complex.
◦Definition in the source file (.cpp):
Complex operator+(Complex P, Complex Q);
Complex operator+(Complex P, Complex Q){ …}
Example – Overlaoding Example – Overlaoding Operator as a Member Operator as a Member FunctionFunctionSince the global function is not part
of the class, accessing private data of the class should be through◦public get functions of the class.◦declaring the global function as a friend
of the class.
Example – Overlaoding Example – Overlaoding Operator as a Global FunctionOperator as a Global FunctionThrough public get functions of the
class class Complex { public: Complex(int=0, int=0); int GetReal(); int GetImaginary(); private: int real, imaginary; };
Complex operator+(Complex P, Complex Q){ return Complex(P.GetReal()+Q.GetReal(), P.GetImginary()+Q. GetImginary());}
Example – Overlaoding Example – Overlaoding Operator as a Global FunctionOperator as a Global FunctionThrough declaring the global
function as a friend of the class. class Complex { friend Complex operator+ (Complex P, Complex Q); public: Complex(int=0, int=0); private: int real, imaginary; };
Complex operator+(Complex P, Complex Q){ return Complex(P.real+Q.real, P.imginary+Q. imginary);}
11.4 Operator Functions as Class 11.4 Operator Functions as Class Members vs. Global MembersMembers vs. Global MembersOverloaded << operator
◦Left operand of type ostream & Such as cout object in cout << classObject
◦Similarly, overloaded >> has left operand of istream &
◦Thus, both must be global functions
11.5 Overloading Stream Insertion 11.5 Overloading Stream Insertion and Stream Extraction Operatorsand Stream Extraction Operators<< and >> operators
◦Already overloaded to process each built-in type and can also process a user-defined class Overload using global, friend functions
Example program◦Class Complex
Holds the real part and the imaginary part; say, 3 and 5.
◦Print out formatted complex number automatically:3 + 5i
ExampleExample class Complex { friend istream &operator>> (istream &in, Complex P); friend ostream &operator<< (ostream &out, Complex P); public: Complex(int=0, int=0); private: int real, imaginary; };
istream &operator>>(istream &in, Complex &P){ in >> P.real >> P.imaginary; return in;}
ostream &operator<<(ostream &out, Complex &P){ out << P.real << “+” << P.imaginary << “i”; return out;}
ExampleExampleIn main():
#include <iostream>
using namespace std;
int main() { Complex P, Q; cin >> P >> Q; cout << P; cout << P << Q; return 0; }
11.4 Operator Functions as Class 11.4 Operator Functions as Class Members vs. Global Members (Cont.)Members vs. Global Members (Cont.)Commutative operators may require + to be commutative◦So both “a + b” and “b + a” work
Suppose we have two different classes◦Overloaded operator can only be
member function when its class is on left Complex + int
Can be member function
◦When other way, need a global overloaded function int + Complex
11.6 Overloading Unary 11.6 Overloading Unary OperatorsOperatorsOverloading unary operators
◦As non-static member function with no arguments Remember, static functions only access static data
◦As global function with one argument Argument must be class object or reference
to class object
11.6 Overloading Unary Operators11.6 Overloading Unary Operators
Example◦ Overload ! to test for empty string◦ If non-static member function, needs no
arguments class String{public: bool operator!() const; …};
!s becomes s.operator!()
◦ If global function, needs one argument bool operator!( const String & ) s! becomes operator!(s)
Example – Overlaoding Example – Overlaoding Operator as a Member Operator as a Member FunctionFunctionOverloading operator+ as member
function◦Prototype in the header file (.h): class Complex
{ public: … bool operator! (); private: int real, imginary; };
bool Complex ::operator!(){ if (real == 0 && imaginary == 0) return true; return false;}
Example – Overlaoding Example – Overlaoding Operator as a Global FunctionOperator as a Global FunctionThrough declaring the global
function as a friend of the class. class Complex { friend bool operator! (Complex P); public: Complex(int=0, int=0); private: int real, imaginary; };
bool operator!(Complex P){ if (P.real == 0 && P.imaginary == 0) return true; return false;}