170 likes | 265 Views
Data Structures - CSCI 102. CS102. C++ Operator. Overloading. Prof Tejada. 1. Data Structures - CSCI 102. Operator Overloading. C++ has tons of built-in operators (e.g. +,-,<<, etc.) They work on built-in types (e.g. int , string ) They don’t work on your own classes!.
E N D
DataStructures-CSCI102 CS102 C++Operator Overloading Prof Tejada 1
DataStructures-CSCI102 OperatorOverloading C++hastonsofbuilt-inoperators(e.g.+,-,<<,etc.) Theyworkonbuilt-intypes(e.g.int,string) Theydon’tworkonyourownclasses! Stringisaclass,sowhydoesthiswork? stringa="hello"; stringb="world!"; stringc=a+b;//addition cout<<c<<endl;//printtoconsole SinceC++doesn’tknowhowtodothisstuffbydefault,we havetotellithow 3
DataStructures-CSCI102 OperatorOverloading Rules Youcanonlyoverloadanoperatorthathasatleastone userdefinedtype(i.e.youcan’toverload"int+int") Youcanonlyoverloadexistingoperators,youcan’t createyourownnewones Alloperatorskeeptheirnormalassociativity& precedence Youcan’toverloadanyofthese :: . -> .* ?: sizeof 4
DataStructures-CSCI102 ThePointClass classPoint { private: intx; inty; public: Point(){x=0;y=0;} Point(intnewx,intnewy){x=newx;y=newy;} intgetX()const{returnx;} intgetY()const{returny;} voidsetX(intnewx){x=newx;} voidsetY(intnewy){y=newy;} }; 5
DataStructures-CSCI102 The+Operator Whenyouseesomethinglikethis: Pointp1(10,10),p2(50,50); Pointp3=p1+p2; Youshouldreallypictureitlikethis: Pointoperator+(constPoint&a,constPoint&b) YoucanimplementalltheoperatorsinC++asafunction callsomewherebehindthescenes ShouldthisfunctionbeamemberofthePointclass? Itcanbe,butitdoesn’treallyneedtobe(nochanges aremadetop1orp2) Couldwegetaccesstotheprivatedataof"a"and "b"withoutbeingpartofclass"Point"? 6
DataStructures-CSCI102 ThefriendKeyword Whatdoesitmeantotagafunctionasafriendofaclass? Thefunctionisn’taclassmemberfunction Thefunctioncanstillaccesstotheprivatedataofthe class Thatsoundslikeahorribleidea! Mostofthetimeitis,butit’susefulforoperatorsthat don’tmodifyclassdata friendfunctionsshouldonlyread"private"class data,theyshouldn’tmodifyit Don’tbreakencapsulation Remember,C++isbuiltforspeed Avoidusingfriendingeneralisprobablynotabad policy 7
DataStructures-CSCI102 ThefriendKeyword classPoint { ... friendPointoperator+(constPoint&a, constPoint&b); ... }; //thisisNOTamemberfunction(noPoint::needed) Pointoperator+(constPoint&a,constPoint&b) { ... } 8
DataStructures-CSCI102 The+=Operator Iftheoperatoractuallychangesoneofitsoperands,it’s betteroffasamemberfunction Pointp1(10,10),p2(50,50); p1+=p2; //we’rechangingp1here Insteadofdefiningitasafriendfunction,wejustdefineit asanormalclassfunction classPoint { ... voidoperator+=(constPoint&b); ... }; 9
DataStructures-CSCI102 TheInsertionOperator(<<) Isn’titannoyingthatthiscodedoesn’tnormallywork? Pointp1(5,10); cout<<p1<<endl; Itcanwork!Overloadtheinsertionoperator(<<)! ostream&operator<<(ostream&out,constPoint&b) NOTE:ostreamisstd::ostreamfrom<iostream> NOTE:cout<<p1<<endlmeans (cout<<p1)<<endl Thisfunctionlooksalotdifferentthantheothers Whatisostream&out? Whyisitnotconst? Whydoesitreturnostream&? NOTE:Itcannotbeaclassmemberfunction 10
DataStructures-CSCI102 TheExtractionOperator(>>) Howcanwereadinsomethingthen? Pointp1; cin>>p1; Overloadtheextractionoperator(>>) istream&operator>>(istream&in,Point&b) NOTE:cin>>p1>>p2means(cin>>p1)>>p2 Thisfunctionlooksalotdifferentthantheothers Whatisistream&in? Whydoesitreturnistream&? WhyisPoint&bnotconst? NOTE:Itcannotbeaclassmemberfunction 11
DataStructures-CSCI102 ComparisonOperators Whataboutcomparingtwoinstancesofaclass? Pointp1(10,10),p2(10,10); if(p1==p2)cout<<"They’reequal!"<<endl; Itstilllookslikewhatwe’reusedto: booloperator==(constPoint&a,constPoint&b) Comparisonalwaysreturnbool Comparisonoperatorscanbereusedtodefineeachother sincemanyofthemactaslogicalopposites ==vs.!= >=vs.< <=vs.> 12
DataStructures-CSCI102 UnaryOperators Someoperatorsonlytakeinasingleargument Pointp1(10,10); Pointp2=-p1; Thislooksabitdifferenttoo: Pointoperator-(constPoint&a) Canalsobe: Pointoperator-() Someotherthingstoconsider WhydoesitreturnaPoint? Whydoesitonlyhaveoneargument? HowdoesC++knowwe’renottryingtoredefine subtractioninstead? Otherunaryoperatorsinclude!and+ 13
DataStructures-CSCI102 WhatOtherStuffCanYouOverload? Prefix/PostfixIncrement/Decrement(++,--) Subscript([]) Pointp1(10,10); cout<<p1[0]; Equality(==) Andmany,manymore 14
DataStructures-CSCI102 point.h #ifndefPOINT_H_ #definePOINT_H_ classPoint { private: intx; inty; public: Point(){x=y=0;} Point(intnewx,intnewy){x=newx;y=newy;} intgetX()const{return intgetY()const{return voidsetX(intnewx){x= voidsetY(intnewy){y= x;} y;} newx;} newy;}
DataStructures-CSCI102 point.h(Cont...) voidoperator+=(constPoint&a); voidoperator+=(constintvalue); int&operator[](constintindex); voidoperator++();//prefix(e.g.++point) voidoperator++(intdummy);//postfix(e.g.point++) Pointoperator-(); booloperator==(constPoint&another_point); booloperator!=(constPoint&another_point); }; Pointoperator+(constPoint&a,constPoint&b); Pointoperator+(constPoint&a,constintb); Pointoperator+(constinta,constPoint&b); std::ostream&operator<<(std::ostream&out,constPoint&b); std::istream&operator>>(std::istream&in,Point&b); #endif/*POINT_H_*/ 18
DataStructures-CSCI102 point.cpp #include<iostream> #include<stdexcept> usingnamespacestd; #include"point.h" Pointoperator+( constPoint&a, constPoint&b) { Pointp; p.setX(a.getX()+b.getX()); p.setY(a.getY()+b.getY()); returnp; Pointoperator+( constinta, constPoint&b) { returnb+a; } ostream&operator<<( ostream&out, constPoint&b) { out<<"("<<b.getX()<<"," <<b.getY()<<")"; returnout; } } istream&operator>>( Pointoperator+( constPoint&a, constintb) { Pointp; p.setX(a.getX()+b); p.setY(a.getY()+b); returnp; } istream&in, Point&b) intx,y; in>>x>>y; b.setX(x); b.setY(y); returnin; { } 19
DataStructures-CSCI102 point.cpp(Cont...) boolPoint::operator==( constPoint&b) { returnx==b.getX()&& y==b.getY(); voidPoint::operator++() { this->x++; this->y++; } } voidPoint::operator++(intdummy) boolPoint::operator!=( constPoint&b) { return!((*this)==b); } voidPoint::operator+=( constPoint&b) { this->x+=b.getX(); this->y+=b.getY(); } PointPoint::operator-() { { ++(*this); } int&Point::operator[]( constintindex) { if(index==0){ returnthis->x; }elseif(index==1){ returnthis->y; } throwout_of_range( "Pointindexwasoutofbounds"); } Pointp; p.setX(-(this->x)); p.setY(-(this->y)); returnp; } 20