Operator oveerloading

709 views
677 views

Published on

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
709
On SlideShare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
13
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Operator oveerloading

  1. 1. 08 c++ Operator Overloading.ppt — Presentation Transcript1. Overloading Operators2. Understanding the Benefits of Overloading Having more than one function with the same name isbeneficial because you can use one easy-to-understand function name without paying attention to thedata types involved Polymorphism allows the same operation to be carried out differently, dependingon the object Some reserve the term polymorphism (or pure polymorphism) for situations in which onefunction body is used with a variety of arguments3. Using the + Operator Polymorphically Separate actions can result from what seems to be the sameoperation or command The + operator has a variety of meanings, which include: Alone before a value(called unary form), + indicates a positive values, as in the expression +7 Between two integers (calledbinary form), + indicates integer addition, as in the expression 5+ 9 Between two floating-point numbers(also called binary form), + indicates floating-point addition, as in the expression 6.4 + 2.14. Overloading Operators— The Rules Operator overloading is the process by which you apply operatorsto your own abstract data types The +, -, *, and / symbols make it easy to work with built-in data typessuch as int and double Classes, however, contain a variety of data members As a result, if you want thecompiler to perform arithmetic with two class objects, you must tell the compiler what you mean Goodprogramming style dictates that you endow the operator with a reasonable meaning5. Overloading Operators— The Rules You overload an operator by making it a function; subsequently,you can use it just like any other function C++ operators are classified as unary or binary, depending onwhether they take one or two arguments, respectively6. Binary Operators that Can Be Overloaded7. Overloading Operators— The Rules Associativity refers to the order in which actions within anexpression are carried out You cannot change associativity when you overload operators You alsocannot change the normal precedence of any operator8. Overloading Operators— The Rules9. Overloading Math Operators When you code an expression such as 4 + 7, C++ understands that youintend to carry out binary integer addition because of the context of the + symbol When you code anexpression such as regularSal + bonus , if C++ can recognize regularSal and bonus as declared doublevariables, then floating-point addition takes place The name of the operator function that overloads the+ symbol is operator+()10. Overloading Math Operators Ex8-111. Overloading Math Operators The operator+() function in Figure 8-1 can work like any other memberfunction When you examine the code for the addTwo() and operator+() functions in Figure 8-1, you seethat the only difference is the function name Instead of the awkward sum = clerk.operator+(driver);, the
  2. 2. operator+() function allows you to leave off the word operator in the function name and add either ofthe following statements: sum = clerk + driver; sum = driver + clerk;12. Overloading Math Operators13. Paying Attention to the Order of the Operands You can choose to overload any of the arithmeticoperators for any classes you develop Then you can use the corresponding operator symbol in a naturalway with class objects14. Overloading an Operator to Work with a Class Object and a Primitive Type When you add twoobjects using the + operator, the objects do not have to be the same type You can add an integer and adouble with an expression such as 5 + 7.84 Ex8-315. Overloading an Operator to Work with a Class Object and a Primitive Type You cannot overloadoperators that work with C++’s built-in data types You cannot overload the + that works with twodoubles to make it do anything but add two doubles Similarly, you can’t overload operators whose firstoperand is an object that is a built-in type, even if the second operand is a class object16. Using Multiple Operations in a Statement Most modern programming languages allow severaloperators to be used in the same statement If you want to sum three values in an older programminglanguage such as assembler or RPG, you first must add two values, producing a temporary total Then, ina separate statement, you add the third value to that total17. The Sale Class Ex8-418. Using Multiple Operations in a Statement Because the associativity of addition occurs from left toright, the attempt to execute the addition highlighted in Figure 8-9 follows this sequence: 1. The left-most + operator is encountered, and C++ recognizes a Sale on each side of the + symbol. The overloadedoperator+() function is called, and saleAmounts for a Shirt and a Tie are added. A double is returned 2.The next + operator is encountered. A Sale object is found as the operand to the right of the +, but adouble value is used as the operand to the left19. Program that Adds Three Sale Objects Ex8-420. Using Multiple Operations in a Statement When the Sale class operator+() function does not return adouble, but instead returns an object of Sale type (as shown in Figure 8-8), the multiple addition workscorrectly The sequence of events now occurs as follows: 1. The left-most + operator is encountered, andC++ recognizes a Sale object on each side of the + symbol. The overloaded operator+() function is called,and saleAmounts for a Shirt and a Tie are added 2. The next + operator is encountered. A Sale objectnow is found on each side of the +—the temporary object returned by the first addition, and the pantsobject 3. The temporary object is assigned to the total Sale object21. Using Multiple Operations in a Statement The results of the execution of the program in Figure 8-9are shown in Figure 8-10 C++ forces you to use the built-in precedence rules for your class operators If
  3. 3. you want to be able to add either a double or a Sale object to a Sale object, then simply write bothversions of the overloaded operator for the class22. Overloading Output The << operator also is overloaded by C++ It is both a bitwise left-shift operatorand an output operator; it is called the insertion operator when used for output The << operator acts asan output operator only when cout (or another output stream object) appears on the left side When youuse cout in a program, you must include #include<iostream.h> The preceding function, calledoperator<<(), returns a reference to ostream23. Overloading Output It accepts two arguments: a reference to ostream (locally named out in thisexample) and an integer (locally named i n in this example) C++ overloads the << operator to work withthe built-in data types; you also may overload the << operator to work with your own classes Tooverload << operator so it can work with a Sale object, you must add the overloaded operator <<()function to the Sale class24. Overloading Output The operator <<() function is a friend to the class of the object it wants to printout, e.g. Sale here.25. Overloading Input If the << operator can be overloaded for output, it makes sense that the >>operator also can be overloaded for input The advantage of overloading operators such as >> is that theresulting programs look cleaner and are easier to read You can create an extraction operator, oroperator>>() function, that uses istream (which is defined in iostream.h, along with ostream) by using aprototype as follows: friend istream& operator>>(istream &in, Sale &Sale);26. Overloaded Operator>>() Function for the Sale Class27. Overloading Input Ex8-628. Overloading ++ and - - With C++, you use ++ to increment variables, and - - to decrement variablesWhen a prefix operator such as ++ is used in an expression, the mathematical operation takes placebefore the expression is evaluated When the postfix operator is used, the expression is evaluated beforethe mathematical operation takes place Within the operator ++() function in the Inventory class, you canwrite the statement that increases numSold in several different ways29. Using the Prefix and Postfix ++ Operators with an Integer30. The Inventory Class31. Overloading ++ and - - The statements numSold++;, numSold = numSold +1;, and numSold += 1; allwould work 8 Ex8-832. Using Postfix Increment and Decrement Operators A problem arises if you want to use a postfix ++operator as well as a prefix ++ operator with a class When you overload any C++ function, you mustsupply different argument lists; for the postfix ++ operator, you use an integer argument The Inventoryclass postfix operator ++() function prototype is: Inventory& operator++(int); Ex8-8
  4. 4. 33. Overloading the = = Operator Writing an operator = =() function should be an easy task You simplydecide what will constitute equality in class members When you create your own classes, you choosewhether equivalency means that every data field must be equivalent, or only specific data members Theoperator = =() function may return either an integer or a boolean variable representing true or false 834. Overloading the = = Operator A variable of type bool can hold one of two values: true or false Someolder C++ compilers do not support the bool type; with those compilers you would use the first versionof operator = =() that returns an integer EX8-935. Overloading the = Operator The = operator can be overloaded for use with your own classes Unlikeother operators, if you don’t define the = operator, C++ provides a definition for you If you want the =operator to do something other than assign each member, then you must create a customeroperator=()function In addition, if the class contains data fields that are pointers, you should create acustom function EX8-936. Overloading [ ] and ( ) The subscript operator , operator[ ], is declared like any other function, butcalled in a manner similar to accessing an array element You can include any instructions you wantwithin an operator [ ] function Typically, you use this function to perform a task that both requires anargument and does not quite fit into another operator’s usual meaning37. The Book Class Ex8-1038. Overloading [ ] and ( )39. Using the Parentheses Operator You can use the parentheses operator to make multipleassignments within a class To overload the parentheses operator to assign both an author and a price toa member of the Book class, you can create the function40. Using the Parentheses Operator

×