Beruflich Dokumente
Kultur Dokumente
4 Operator Overloading
4.1 Objectives of the lab:
Introducing the concepts of operator overloading and overloading different operators such as
16 Arithmetic operators
17 Relational operators
18 Logical operators
19 Unary operators
4.2 Pre-Lab
void main()
{
complex c1(3, 4.3), c2(2, 4);
c1.show();
c2.show();
complex c3;
c3=c1+ c2; //Invocation of "+" Operator -- direct
//or
//c3=c1.operator+ (c2); //Invocation of "+" Operator -- Function
c3.show();
}
TYPE operator OP ()
{
body of function
}
complex():re(0), im(0)
{}
complex(double r, double i):re(r), im(i)
{}
void show()
{
cout<<"complex number: "<<re<<"+"<<im<<"i"<<endl;
}
4.2.6 How can the above program be modified to allow for a statement like
c2=++c1;?
4.3 In-Lab
4.3.1 Activity
Create a class RationalNumber that stores a fraction in its original form (i.e. without finding the
equivalentfloatingpointingresult).Thisclassmodelsafractionbyusingtwodatamembers:aninteger
fornumeratorandanintegerfordenominator.Forthisclass,providethefollowingfunctions:
b) Atwoargumentconstructorthatinitializesthenumeratoranddenominatortothevaluessent
fromcallingfunction.Thisconstructorshouldpreventa0denominatorinafraction,reduceor
simplifyfractionsthatarenotinreducedform,andavoidnegativedenominators.
c) Adisplayfunctiontodisplayafractionintheformata/b.
d) Anoverloadedoperator+foradditionoftworationalnumbers.
Twofractionsa/bandc/dareaddedtogetheras:
a c a * d b * c
b d b*d
e) Anoverloadedoperatorforsubtractionoftworationalnumbers.
Twofractionsa/bandc/daresubtractedfromeachotheras:
a c a * d b * c
b d b*d
f) Anoverloadedoperator*forsubtractionoftworationalnumbers.
Twofractionsa/bandc/daremultipliedtogetheras:
a c a*c
*
b d b*d
g) Anoverloadedoperator/fordivisionoftworationalnumbers.
Iffractiona/bisdividedbythefractionc/d,theresultis
a a*d
b c b*c
d
h) Overloadedrelationaloperators
a. operator >: should return a variable of type bool to indicate whether 1st fraction is
greaterthan2ndornot.
b. operator <: should return a variable of type bool to indicate whether 1st fraction is
smallerthan2ndornot.
c. operator >=: should return a variable of type bool to indicate whether 1st fraction is
greaterthanorequalto2ndornot.
i) OverloadedequalityoperatorsforRationalNumberclass
e. operator==: should return a variable of type bool to indicate whether 1st fraction is
equaltothe 2ndfractionornot.
f. Operator!=:shouldatruevalueifboththefractionsarenotequalandreturnafalseif
bothareequal.
4.3.2 Activity
CreateaclasscalledTimethathasseparateintmemberdataforhours,minutes,andseconds.Provide
thefollowingmemberfunctionsforthisclass:
a) Anoargumentconstructortoinitializehour,minutes,andsecondsto0.
b) A3argumentconstructortoinitializethememberstovaluessentfromthecallingfunctionat
the time of creation of an object. Make sure that valid values are provided for all the data
members.Incaseofaninvalidvalue,setthevariableto0.
c) Amemberfunctionshowtodisplaytimein11:59:59format.
e) Overloadedoperatorsforpreandpostincrement.Theseincrementoperatorsshouldadda1
tothesecondsunitoftime.Keeptrackthatsecondsshouldnotexceed60.
f) Overloadoperatorsforpreandpostdecrement.Thesedecrementoperatorsshouldsubtracta
1 from seconds unit of time. If number of seconds goes below 0, take appropriate actions to
makethisvaluevalid.
Amain()programsshouldcreatetwoinitializedTimeobjectsandonethatisntinitialized.Thenit
shouldaddthetwoinitializedvaluestogether,leavingtheresultinthethirdTimevariable.Finallyit
shoulddisplaythevalueofthisthirdvariable.Checkthefunctionalitiesof++andoperatorsofthis
programforbothpreandpostincrementation.
4.4 Home-Lab
4.3.3 Activity
CreateaclasscalledDistancecontainingtwomembersfeetandinches.Thisclassrepresentsdistance
measuredinfeetsandinches.Forthisclass,providethefollowingfunctions:
f) Anoargumentconstructorthatinitializesthedatamemberstosomefixedvalues.
g) A2argumentconstructortoinitializethevaluesoffeetandinchestothevaluessentfromthe
callingfunctionatthetimeofcreationofanobjectoftypeDistance.
h) Overloadedarithmeticoperators
a. operator+ to add two distances: Feet and inches of both objects should add in their
corresponding members. 12 inches constitute one feet. Make sure that the result of
additiondoesntviolatethisrule.
b. operator+=foradditionoftwodistances.
i) overloadedrelationaloperators
a. operator >: should return a variable of type bool to indicate whether 1st distance is
greaterthan2ndornot.
b. operator <: should return a variable of type bool to indicate whether 1st distance is
smallerthan2ndornot.
c. operator >=: should return a variable of type bool to indicate whether 1st distance is
greaterthanorequalto2ndornot.
d. operator<=: shouldreturnavariableoftypebooltoindicatewhether1stdistanceis
smallerthanorequalto2ndornot.
j) Overloadedequalityoperators
a. operator==: should return a variable of type bool to indicate whether 1st Distance is
equaltothe 2nddistanceornot.
b. Operator!=:shouldatruevalueifboththedistancesarenotequalandreturnafalseif
bothareequal.
4.3.4 Activity
Letusmodeldigitalstorage.Digitaldataisstoredintheformofbits.8bitsconstituteonebyte.Createa
classStoragethatspecifiesthesizeofafile.Thisclasshastwointegerdatamembers:bitsandbytes.
g) Provideanoargumentconstructortoinitializethesizeofsomefileto0bitsand0bytes.
h) Provideatwoargumentconstructortoinitializethesizeofafiletovaluesspecifiedatthetime
ofcreationofanobject.
i) Provideanoverloadedoperator+thatisusedtomergetwofilestogetherinathirdfile.
j) Provideanoverloadedoperator+=thatisusedtoconcatenateonefileattheendoftheother.
k) Provideoverloadedpostincrementandpreincrementoperatorstoincrementthesizeofafile
byonebit.(Youmustwritethefunctionstoaccommodatestatementslikef2=++f1;andf2=f1++;
wheref1andf2areinstancesoftheclassStorage)
l) Provideanoverloadedoperator>todeterminewhetheronefileislargerinsizethantheother.
Writeatestprogramtotestthefunctionalityofthisclass.
4.5 References:
9 Classnotes
10 ObjectOrientedProgramminginC++byRobert Lafore(Chapter8)
11 HowtoProgramC++byDeitel & Deitel (Chapter8)