Download presentation
Presentation is loading. Please wait.
Published byRaymond Martin Modified over 8 years ago
1
Friend Functions
2
Problem u Assuming two Complex objects u How would one add two numbers? W + X Complex operator+(const Complex& w, const Complex& x); Whose member function is it? W? X? Whose data elements are changed? W? X? Neither; The operation is outside both W and X A similar operation:cout << W;
3
Solution: u A "compromise" mechanism –Class granting non-member function permission to access its data members. u By –Declaring non-member function within class –Preceding its declaration with keyword friend.
4
Friend Functions u not member functions of class X u have access to data members in class X u named as a friend in class X’s header u defined in class X’s implementations file u "outside" an object –When friend function operates on an object it receives the object via a parameter.
5
Friend functions declared within class (prepend friend ) friend int operator< (const Strings& S1, const Strings& S2); defined in implementation file (no friend, no ::) int operator< (const Strings& S1, const Strings& S2) u See friend/strings.h & strings.cpp
7
19. Differentiate among member functions, global functions and friend functions. u Virtual functions must be members u operator>> & operator<< are never members u Only non-member functions get their type conversions on their left-most argument Rational r = 2 * Rational(3,4); operarator* must be Friend or auxiliary function u Everything else should be member functions
8
Friend example /***** I/O Functions *****/ /* --- ostream output Receives: An ostream Out and a Time object T Output: data members of Time object in standard format. Passes back:ostream Out with T inserted Return value: Out *************************************************/ friend ostream& operator<<(ostream& Out, const Time& T); Definition in Time.cpp remains unchanged.
9
Overloading Output for Objects How could we output an object using cout << "We'll be eating at " << MealTime << endl; instead of cout << "We'll be eating at " ; MealTime.PrintTime(); cout << endl;
10
A First Attempt: Put new function in Time.h /***** I/O Functions ******/ /* --- ostream output Receives: An ostream Out and a Time object T Output: The data members of a Time object in standard format. Passes back: The ostream Out with T inserted Return value: The ostream Out*/ ostream& operator<<(ostream& Out, const Time& T); // We're not finished with this declaration // Note: first use of a Time object as a parameter
11
Place definition in Time.cpp //----- Function to implement ostream output ---- ostream& operator<<(ostream& Out, const Time& T) { Out << T.Hour_ << ':' << (T.Minute_ < 10 ? "0" : "") << T.Minute_ << ' ' << T.AMorPM_ << ".M. (" << (T.MilTime_ < 100 ? "0" : "") << T.MilTime_ << " mil. time)”; return Out; }
12
Problem u cout << MealTime; << is a function call with two actual params: cout, MealTime u ostream& operator<<(ostream& Out, const Time& T); –(assuming defined as a member function in Time.cpp) –is a function of three parameters: Out, T, and MealTime object (implicitly)
13
u All member functions receive the object as an implicit parameter. MealTime.Set(5,30,’P’); // a function call with 3 actual params + 1 param passed implicitly (MealTime) void Time::Set(unsigned Hours, unsigned Mins, char AMPM) // a function heading with 3 formal params + 1 implicit formal param (a Time obj)
14
Compiler error u Overloaded function will not to compile –an overloaded operator definition –cannot change the number of operands an operator takes Compiling TIME.CPP: Error TIME.H 84: 'Time::operator <<(ostream &,const Time &)' must be declared with one parameter Compiler only wants the ostream, it will get the Time from the class in which it is imbedded.
15
Output example Time MealTime, BedTime(11, 30, 'P');... MealTime.Set(5, 30, 'P'); cout << "Eat at " << MealTime << "\nand sleep at " << BedTime; Execution: Eating at 5:30 P.M. (1730 mil. time) and sleep at 11:30 P.M. (2330 milt time)
16
Time Class Input: In Time.h, declare operator>>( ) as a friend function: /* --- istream input Receives:An istream In and a Time object T Input:Values for the data members of T. Passes back:istream In with values removed T with values stored in data members Return value:In Note: Input times in format hh:mm xM ***************************************************/ friend istream& operator>>(istream& In, Time& T);
17
Add to Time.cpp //----- Function to implement istream input ---- istream& operator>>(istream& In, Time& T) { int Hours, Minutes; char Ch,// gobbles up extra characters AMPM; In >> Hours >> Ch >> Minutes >> AMPM >> Ch; T.Set(Hours, Minutes, AMPM); return In; }
18
Time MealTime, BedTime;... cout << "Enter meal time and bedtime (hh:mm xM): "; cin >> MealTime >> BedTime; cout << "We'll be eating at '' << MealTime << endl; cout << "We'll hit the hay at " << BedTime << endl; Execution: Enter meal time and bedtime (hh:mm xM): 5:30 PM 11:30 PM We'll be eating at 5:30 P.M. (530 mil. time) We'll hit the hay at 11:30 P.M. (2330 milt time) Enter meal time and bedtime (hh:mm xM): 5:30 PM 12:15 AM We'll be eating at 5:30 P.M. (530 mil. time) We'll hit the hay at 12:15 A.M. (015 mil. time)
19
Class Scope Rule: u Members of a class are local to the class. u Private members can be accessed only within class –by member functions –by friends of the class u Public members class can be accessed outside using dot notation
20
Summary of our Time Class: u OperationName (ThingsNeeded ) --> (ThingsProduced) u Constructors –Constructor: () --> Time –Constructor: (Hours, Minutes, AMPM) --> Time –Set(Time, Hours, Minutes, AMPM) --> Time u Extractors: –Hour(Time) --> Integer –Minute(Time) --> Integer –AMorPM(Time) --> Character –MilTime: (Time) --> Integer u Input/Output: –Output: (ostream,Time) --> ostream –Input: (istream,Time) --> (Time, istream)
21
Adding Relational Operator: < Less-than: (Time, Time) --> Boolean Receives: Two Time objects Returns: True if first Time object is less than second; false otherwise.
22
Is operator< a member function? Does it belong inside the Time class? –it can operate on a Time object that contains it Does it belong outside the class? –it can operate on any Time object Answer: The latter. Not a member function.
23
Is operator< a friend function? Does it need access to data members? Answer: Yes.
24
Add to Time.h: /***** Relational operators *~***/ /* --- operator< determines if one Time is less than another Time Receive: Times T1 and T2 Return: True (1) if T1 < T2, false (O) otherwise. */ friend short operator<(const Time& T1, const Time& T2) { return (Tl.MilTime_ < T2.MilTime_); }; Because of simplicity of this function we put it its definition in Time.h.
25
Adding Advance Function u Advance: (Time, Hours, Minutes) --> Time –Increments Time object by Hours / Minutes u Should it be a member function? –Does it belong inside the Time class –from which it can operate on the Time object that contains it? u Answer: Yes
26
Add to Time.h: /***** Increment operator *****/ /* --- Advance() increments a Time by a specified value. Receive: Hours, the number of hours to add Minutes, the number of minutes to add Return: The Time object containing this function with its data members incremented by these values. */ void Advance(unsigned Hours, unsigned Minutes);
27
Advance ( ) increments MilTime_ and converts military time to corresponding standard time and sets Hour_, Minute_, and AMorPM_. //----- Function to implement Advance() ------ void Time::Advance(unsigned Hours, unsigned Minutes) { MilTime_ += 100 * Hours + Minutes; unsigned MilHours = MilTime_ / 100, MilMins = MilTime_ % 100; MilHours += MilMins / 60; MilMins %= 60; MilHours %= 24; MilTime_ = 100 * MilHours + MilMins; ToStandard(MilTime_, Hour_, Minute_, AMorPM_); }
28
ToStandard( ) Conversion from military to standard time may be useful in other operations We add another utility function: ToStandard ( ) a counterpart to ToMilitary():
29
Add declaration & def. to Time.cpp void ToStandard(unsigned MilTime, unsigned& Hours, unsigned& Minutes, char& AMPM); /*--- ToStandard converts military time to standard. Receive: A military time MilTime Return: Corresponding std time, Hours, Mins, AMPM */ void ToStandard(unsigned MilTime, unsigned& Hours, unsigned& Minutes, char& AMPM) { Hours = (MilTime / 100) % 12; if (Hours == 0) Hours = 12; Minutes = MilTime % 100; AMPM = (MilTime / 100) < 12 ? 'A' : 'P'; }
30
Testing cout << "Meal time < Bed time? " << (Mealtime < BedTime ? "TRUE\n" : "FALSE\n"); MealTime.Advance(5,15); cout << "New meal time " << MealTime << endl; cout << "Meal time < Bed time? "; << (Mealtime < BedTime ? "TRUE\n" : "FALSE\n"); Execution: Enter meal time and bedtime (hh:mm xM): 6:00 PM 11:00 PM We'll be eating at 6:00 P.M. (1800 mil. time) We'll hit the hay at 11:00 P.M. (2300 mil. time) Meal time < Bed time? TRUE New meal time 11:15 P.M. (2315 milt time) Meal time < Bed time? FALSE
31
More to come? u Possible additions v remaining relational operators v ++ operator v = (in place of set ( ) ) v + v += (in place of Advance ( ) )
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.