1 / 17

Data Structures - CSCI 102

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!.

roddy
Download Presentation

Data Structures - CSCI 102

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. DataStructures-CSCI102 CS102 C++Operator Overloading Prof Tejada 1

  2. 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

  3. DataStructures-CSCI102 OperatorOverloading Rules Youcanonlyoverloadanoperatorthathasatleastone userdefinedtype(i.e.youcan’toverload"int+int") Youcanonlyoverloadexistingoperators,youcan’t createyourownnewones Alloperatorskeeptheirnormalassociativity& precedence Youcan’toverloadanyofthese :: . -> .* ?: sizeof 4

  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

  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

  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

  7. DataStructures-CSCI102 ThefriendKeyword classPoint { ... friendPointoperator+(constPoint&a, constPoint&b); ... }; //thisisNOTamemberfunction(noPoint::needed) Pointoperator+(constPoint&a,constPoint&b) { ... } 8

  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

  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

  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

  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

  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

  13. DataStructures-CSCI102 WhatOtherStuffCanYouOverload? Prefix/PostfixIncrement/Decrement(++,--) Subscript([]) Pointp1(10,10); cout<<p1[0]; Equality(==) Andmany,manymore 14

  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;}

  15. 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

  16. 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

  17. 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

More Related