operator overloads part2. issue provide member +(int) operator rational + int ok int + rational...
TRANSCRIPT
Compiler View
• What compiler sees
r2 + 4r2.operator+(4) call + function on r2, pass it 4
4 + r24.operator+(r2) call + function on 4?!?!?
Overload Options
• Overload operator as member:• r1 + r2 interpreted as r1.operator+(r2)
• Overload operator as non-member:• r1 + r2 interpreted as +(r1, r2)
Overload Option 2
• Provide operator as non-member function• r1 + r2 interpreted as +(r1, r2)
NOT a member. No Rational::
Option 2 Implementation
• Standard function• r1 + r2 interpreted as +(r1, r2)
– Need two parameters
– No private access
Option 2 Advantage
• Standard function operator can place class last:
• Compiler view:
4 + r2
+(4, r2) Call + function with 4 and r2
Which Option?
• Implement operators as members or functions?
• No perfect answer…– Members : • Access to private data• First operand is implicit – must be your type
– Standard function• First operand can be other type• Normally don't have access to privates…
Friends With Benefits
• Friend's of a class have access to its privates:
OK if B is A's friend
Private access not allowed
Friend +
• Can declare functions as friends:–Declares function–Makes friend of class
–Givesprivateaccess:
+ int without operator
• With non-member function, compiler will implicitly construct objects to make operators work:
Type Conversions
• Conversion operators define how to cast away from Rational – Written as member function– Return type used as operator name
LValues and RValues
• LValues : Things that can be on left side of =– Variables, other storage
• RValues : Everything else– Temporary values
IO Operators
• Most classes should not do direct IO– No knowledge of context they will be used in
• toString() function better but clunky
IO Operators
• Most classes should not do direct IO– No knowledge of context they will be used in
• toString() function better but clunky
• Want to directly output/input:
IO Overloads
• Stream always leftoperand of insertion /extraction operators:Must overload << >> as friends
IO Overloads
• Overloading << >>
– ostream means any output stream• File, cout, stringstream…
– istream any input stream– Return reference to the stream to allow chaining
IO Overloads
• Overloading << >>
– ostream means any output stream• File, cout, stringstream…
– istream any input stream– Return reference to the stream to allow chaining
cout
Output
• Stream insertion:– Pick info to send to stream– Return the stream (as reference)– Friend, so has private access
Input• Stream extraction:– Read what you want from stream
• May discard some
– Modify object passed as reference– Return the stream (as reference)