1 / 53

Operator Overloading; String and Array Objects

22. Operator Overloading; String and Array Objects. OBJECTIVES. In this chapter you will learn: What operator overloading is and how it makes programs more readable and programming more convenient. To redefine (overload) operators to work with objects of user-defined classes.

aundreaj
Download Presentation

Operator Overloading; String and Array Objects

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 22 • OperatorOverloading;String and ArrayObjects

  2. OBJECTIVES In this chapter you will learn: • What operator overloading is and how it makes programs more readable and programming more convenient. • To redefine (overload) operators to work with objects of user-defined classes. • The differences between overloading unary and binary operators. • To convert objects from one class to another class. • When to, and when not to, overload operators. • To use overloaded operators and other member functions of standard library class string.

  3. 22.1 Introduction • 22.2 Fundamentals of Operator Overloading • 22.3 Restrictions on Operator Overloading • 22.4 Operator Functions as Class Members vs. Global Functions • 22.5 Overloading Stream Insertion and Stream Extraction Operators • 22.6 Overloading Unary Operators • 22.7 Overloading Binary Operators • 22.8 Case Study: Array Class • 22.10 Case Study: String Class • 22.13 Standard Library Class string

  4. 22.1 Introduction and Motivation • C++ provides a rich set of built-in operators • Provide programmers with a concise notation for expressing manipulations of data of fundamental types • x + y*z versus multiply y by z and add the result to x • C++ allows the programmer to redefine the meaning of the operators when applied to objects of class type • operator overloading: use operators with class type objects • Clearer than function calls for certain classes • Make programs more readable and programming more convenient • Examples << • bitwise left-shift for built-in data types • Stream insertion for cout + • Performs arithmetic on multiple items (integers, floats, complex numbers, etc.) • String concatenation: s1 + s2 • Java doesn’t support the feature of operator overloading.

  5. 22.1 Introduction and Motivation class complex { double re, im; public: complex(double r, double i) : re(r), im(i) {} complex operator+ (complex); complex operator*(complex); }; void f () { complex a = complex(1, 3.1); complex b = complex(1.2, 2); complex c = b; a = b+c; b = b + c*a; c = a*b + complex(1, 2); }

  6. 22.2 Fundamentals of Operator Overloading • Programmers cannot create new operators • Overloaded operators are in fact functions with special names • Create a function for the class: operator functions • Name of operator function must be • Keyword operator followed by symbol for the operator being defined • Example: operator+ for the addition operator + • Operator function also has a return type and a parameter list • Example: Sales_item is a user-defined class type Sales_item operator+(const Sales_item&, const Sales_item&); • Operator functions can be member functions or global functions

  7. Fig. 22.2| Operators that cannot be overloaded. Fig. 22.1| Operators that can be overloaded.

  8. Good Programming Practices • Use operator overloading when it makes a program clearer than accomplishing the same operations with function calls. • Overloaded operators should mimic the functionality of their built-in counterparts—for example, the + operator should be overloaded to perform addition, not subtraction. • Avoid excessive or inconsistent use of operator overloading, as this can make a program cryptic and difficult to read.

  9. 22.2 Fundamentals of Operator Overloading (Cont.) • Using operators on a class object, that operator MUST be overloaded for that class • Three exceptions: (can also be overloaded by the programmer) • 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 • Returns the value of the expression to its right • Three operators {= & , } can be used without explicit overloading • Overloading provides concise notation • object2 = object1.add( object2 );vs. object2 = object2 + object1;

  10. 22.3 Restrictions on Operator Overloading • As shown in Slide 6, some operators cannot be overloaded • There are some other restrictions: • Something cannot be changed by operator overloading • Precedence of operator (order of evaluation) cannot be changed • E.g., x == y+z always binds y and z to operator+, and uses that result as the right-hand operand to operator== • Associativity (left-to-right or right-to-left) cannot be changed • Number of operands cannot be changed • E.g., & is unary, can only act on one operand • The meaning of the operators for built-in data types cannot be changed • E.g., int operator+(int, int) is illegal • Cannot create new operators • It is illegal to attempt to define an operator** • Operators must be overloaded explicitly • Overloading + and = does not imply that += is also overloaded

  11. Software Engineering Observation 22.2 • At least one argument of an operator function must be an object or reference of a user-defined type. This prevents programmers from changing how operators work on fundamental types.

  12. 22.4 Operator Functions as Class Members vs. Global Functions • Two types of overloaded operators: unary operator and binary operator • Unary operator function “should” have one parameter • Binary operator function “should” have two parameters • Overloaded operators may be defined as class member functions or global functions • Operators that are class member functions have an implicit this parameter that is bound to the first operand. So: • An overloaded unary operator has no explicit parameter if it is a member function, and one parameter if it is a global function • An overloaded binary operator has one explicit parameter if it is a member function, and two parameters when defined as a global function

  13. 22.4 Operator Functions as Class Members vs. Global Functions • Rules: • Operators { =()[]->} must be overloaded as a class member function • Other operators can be overloaded as either class member functions or global functions. • Operator functions • As member functions • Use this keyword to implicitly get left operand argument • Called when • Single operand of unary operator is of this class • Left operand of binary operator is of this class • As global functions • Need parameters for all operands • Can be a friend to access private or protected data (for performance reasons)

  14. 22.4 Why Global Functions? • How to support cout << Sales_item ? • Overloaded << operator (stream insertion) • Left operand of << has type ostream& • Similarly, overloaded >>(stream extraction) has left operand of istream & • Thus, both << and >> must be global functions class Sales_item { friend std::ostream& operator<<(std::ostream&, const Sales_item&); friend std::istream& operator>>(std::istream&, const Sales_item&); public: Sales_item& operator+=(const Sales_item&); };

  15. 22.4 Why Global Functions? • Commutative operators • May want + 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 • HugeIntClass + long int • operator+ can be member function of HugeIntClass • When other way, need a global overloaded function • long int + HugeIntClass

  16. Overloaded Operator Design • Most operators have no meaning for class objects • The class designer should decide which, if any, operators to support. • Input and output are normally done by overloading the shift operators << and >> • An operation to test whether the object is empty could use operator! • If a class has an arithmetic or bitwise operator, it will be a good idea to provide the corresponding compound assignment operator (e.g., +=) • Equality and relational operators (==, !=, <, >, <=, >=)

  17. Overloaded Operator Design • Member function or global function? • The assignment =, subscript [], call (), and member access arrow -> operators MUST be defined as member functions • Compound-assignment operators ordinarily ought to be member functions (but not required to be so) • Other operators that change the state of their object or that are closely tied to their given type – such as increment, decrement, and dereference – usually should be member functions • IO operators (<< and >>) must be global functions • Symmetric operators, such as the arithmetic, equality, relational, and bitwise operators, are best defined as ordinary global functions

  18. 22.5 Overloading Stream Insertion and Stream Extraction Operators • Classes that support I/O ordinarily should do so by using the same interface as defined by the iostream library for the built-in types • Many classes provide overloaded instances of the input and output operators • << and >> operators • Already overloaded to process each built-in type • Can also process a user-defined class • Overload using global, friend functions • Example program • Class PhoneNumber • Holds a telephone number • Print out formatted number automatically (123) 456-7890

  19. Outline PhoneNumber.h (1 of 1) Notice function prototypes for overloaded operators >> and << (must be global, friend functions), because they need to access nonpublic data members.

  20. Outline Allows cout << phone; to be interpreted as: operator<<(cout, phone); PhoneNumber.cpp (1 of 2) Display formatted phone number The second parameter of << should be a const reference to the class type we want to print. Using reference: to avoid copying the argument. Being constant: the object should not be changed by this operator function.

  21. Outline ignore skips specified number of characters from input (1 by default) PhoneNumber.cpp (2 of 2) Input each portion of phone number separately The second parameter of >> should be a nonconst reference to the class type we want to print. Using reference: to avoid copying the argument. Being nonconstant: the purpose of an input operator is to read data into the object

  22. Outline fig22_05.cpp (1 of 2) Testing overloaded >> and << operators to input and output a PhoneNumber object

  23. Outline fig22_05.cpp (2 of 2)

  24. Software Engineering Observation 22.3 • New input/output capabilities for user-defined types are added to C++ without modifying C++’s standard input/output library classes. This is another example of the extensibility of the C++ programming language.

  25. 22.6 Overloading Unary Operators • Overloading unary operators • Can overload as non-static member function with no arguments • Remember, static functions can only access static data members of the class • Or, can overload as global function with one argument • Argument must be class object or reference to class object

  26. 22.6 Overloading Unary Operators (Cont.) • 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 • booloperator!( const String & ) • !s becomes operator!(s)

  27. 22.7 Overloading Binary Operators • Overloading binary operators • If non-static member function, with one argument • If global function, with two arguments // + is overloaded as a global function for class Sales_item Sales_item operator+(const Sales_item& lhs, const Sales_item& rhs) { Sales_item ret(lhs); // copy lhs into a local object that we will return ret += rhs; // += is overloaded as a member function return ret; }

  28. 22.7 Overloading Binary Operators (Cont.) • Example: Overloading += • If non-static member function, needs one argument • class String{public: const String & operator+=( const String & ); …}; • y += z becomes y.operator+=( z ) • If global function, needs two arguments • const String &operator+=( String &, const String & ); • y += z becomes operator+=( y, z )

  29. 22.8 Case Study: Array Class • Pointer-based arrays in C++ • No range checking • Cannot be compared meaningfully with == • No array assignment (array names are const pointers) • If array passed to a function, size must be passed as a separate argument • Example: Implement an Array class with • Range checking • Array assignment • Arrays that know their own size • Outputting/inputting entire arrays with << and >> • Array comparisons with == and !=

  30. 22.8 Case Study: Array Class (Cont.) • Copy constructor • Used whenever copy of object is needed: • Passing by value (return value or parameter) • Initializing an object with a copy of another of same type • Array newArray( oldArray ); orArray newArray = oldArray (both are identical) • newArray is a copy of oldArray • Prototype for class Array • Array( const Array & ); • Must take reference • Otherwise, the argument will be passed by value… • Which tries to make copy by calling copy constructor… • Infinite loop

  31. Outline Array.h (1 of 2) Most operators overloaded as member functions (except << and >>, which must be global functions) Prototype for copy constructor != operator simply returns opposite of == operator – only need to define the == operator

  32. Outline Array.h (2 of 2) Operators for accessing specific elements of Array object

  33. Outline Array.cpp (1 of 6)

  34. Outline Array.cpp (2 of 6) We must declare a new integer array so the objects do not point to the same memory

  35. Outline Array.cpp (3 of 6) Want to avoid self assignment This would be dangerous if this is the same Array as right

  36. Outline Array.cpp (4 of 6) integers1[ 5 ] calls integers1.operator[]( 5 )

  37. Outline Array.cpp (5 of 6)

  38. Outline Array.cpp (6 of 6)

  39. Outline fig22_08.cpp (1 of 5) Retrieve number of elements in Array Use overloaded >> operator to input

  40. Outline Use overloaded << operator to output fig22_08.cpp (2 of 5) Use overloaded != operator to test for inequality Use copy constructor Use overloaded = operator to assign

  41. Use overloaded == operator to test for equality Outline fig22_08.cpp (3 of 5) Use overloaded [] operator to access individual integers, with range-checking

  42. Outline fig22_08.cpp (4 of 5)

  43. Outline fig22_08.cpp (5 of 5)

  44. Software Engineering Observation 22.5 • A copy constructor, a destructor and an overloaded assignment operator are usually provided as a group for any class that uses dynamically allocated memory.

  45. Common Programming Error 22.8 • Not providing an overloaded assignment operator and a copy constructor for a class when objects of that class contain pointers to dynamically allocated memory is a logic error.

  46. 22.13 Standard Library Class string • provided by C++ Standard Library • Available for anyone to use • Class string • Header <string>, namespace std • using std::string • Can initialize string s1( "hi" ); • Overloaded << (as in cout << s1) • Overloaded >> (as in cin>> s1) • Overloaded relational operators • ==, !=, >=, >, <=, < • Assignment operator = • Concatenation (overloaded + and +=)

  47. 22.13 Standard Library Class string • Ways to initialize string

  48. 22.13 Standard Library Class string • string operations

  49. 22.13 Standard Library Class string (Cont.) • Class string (Cont.) • Substring member function substr • s1.substr( 0, 14 ); • Starts at location 0, gets 14 characters • s1.substr( 15 ); • Substring beginning at location 15, to the end • Overloaded [] • Access one character • No range checking (if subscript invalid) • Member function at • Accesses one character • Example • s1.at( 10 ); • Has bounds checking, throws an exception if subscript is invalid • Will end program (learn more in Chapter 16)

  50. Outline fig22_15.cpp (1 of 4) Passing strings to the string constructor Create empty string

More Related