Вы находитесь на странице: 1из 4

Software Design Lecture Notes Overloading Operators in C++

Prof. Stewart Weiss

Overloading Operators in C++


Stewart Weiss Defining the Overloaded Operators C++ provides a standard set of operators for its built-in types, like +, /, and %. When you begin to learn programming, you learn that the "/" in x ! / " is the integer division operator. C++ overloads some of these operators itself. #hus, in "x !.$ / %" the "/" is the floating point division operator, not the integer division operator. &t behaves differently be'ause the result is a floating point number, not an integer. (ometimes, )hen you 'reate a 'lass to represent an appli'ation ob*e't, you often find yourself thinking that it )ould be ni'e if you also 'ould extend the meanings of some of those standard operators so that they represented similar operators for that type of ob*e't. +or example, it is useful to add points, fra'tions, ve'tors, or matri'es using the same notation as )e use for adding numbers. Wouldn,t it be easy to understand the follo)ing bit of 'ode if the operators had the natural meaningPoint p,q; cin >> p >> q; cout << "The sum of " << p << " and " << q << " is " << p+q << endl;

&f you kno) a bit about matrix algebra then you kno) that the sum of t)o points is the point that you get by thinking of ea'h point as a ve'tor )ith its sour'e at the origin and its end at the point, and putting the sour'e of one ve'tor at the head of the other, as in the follo)ing pi'ture.

p+q p + q

#he points p and . are represented by ve'tors from the origin /$,$0. #heir sum is the ve'tor starting at the origin sho)n above. 1verloads do not provide any extra 'omputational po)er for a 'lass. #hey are nothing more than a notational 'onvenien'e that makes it more natural for the 'lient programmer to )rite 'ode. & )ill demonstrate ho) to use overloaded operators )ith a very simple 'lass named CPoint that represents t)o-dimensional points. #he CPoint 'lass interfa'e that follo)s demonstrates ho) the overloads 'an be a'hieved.

Software Design Lecture Notes Overloading Operators in C++

Prof. Stewart Weiss

class CPoint { private: int h; int v; public: CPoint(int x !, int " CPoint(const CPoint$ P #; CPoint$ operator+ (const CPoint operator (const dou(le operator(# (const

!#; %%cop" const&ucto& CPoint$ '#; CPoint$ C#; dou(le )#;

friend ost&eam$ operator<<(ost&eam$ out,CPoint$ P#; friend CPoint operator+ (const CPoint$ lhs, const CPoint$ &hs#; *;

&n this interfa'e, the follo)ing operators are overloaded3


+ :: + +, si-eof t"peid 5ven the ne. and delete operators 'an be redefined by the user6 (# + << 4ot all C++ operators 'an be overloaded. #he ones that 'annot be redefined by the user are3

Implementing the Overloads +irst noti'e that there are t)o )ays in )hi'h operators are overloaded in the above example. 1ne )ay is to make the overloaded operator a member of the 'lass itself. #he other )ay is to make it a non-member, but a friend, of the 'lass. &f you make the operator a member of the 'lass, it has an impli'it argument that is the 'lass ob*e't itself. #o demonstrate,
class C {
C operator+ (C#;%% + is a (ina&" ope&ato& .ith ,this as left ope&and C operator/ (C,C#; %% e&&o& // this ma0es ope&ato&/ a te&na&" ope&ation+

*; C operator,(C,C#; %% , is a (ina&" non/mem(e& ope&ato&

(o in the above example, there are three member operators, + , , and /0, and t)o non-members, + and 77, implemented as friends of the 'lass. (ome of the operators re.uire more explanation than others. & )ill explain ho) to implement them by example. #o start, here is the first implementation. 8

Software Design Lecture Notes Overloading Operators in C++

Prof. Stewart Weiss

CPoint CPoint::ope&ato& (const CPoint$ P# %%ove&load assi1nment ope&ato& { this/>h P+h; this/>v P+v; return ,this; *

#he assignment operator is re.uired to return a value. &n this 'ase it returns its result by value rather than by referen'e. &n essen'e, it is 'opying the members of the argument ob*e't 9 into the ob*e't on )hi'h it is 'alled. &f you )rite
q p;

it really means q+ope&ato& (p#, meaning, p is 'opied into .. #he this pointer is a pointer to the ob*e't on )hi'h the 'all )as made. #here is no other )ay to return a 'opy of this ob*e't. #he next example sho)s that this 'ould be done by referen'e as )ell.
CPoint$ CPoint:: ope&ato&+ (const CPoint$ P# { this/>h + P+h; this/>v + P+v; return ,this; *

&t )orks *ust as )ell be'ause the this pointer does not point to an ob*e't that )ill disappear )ithin the lifetime of the 'all on )hi'h it is made. &n other )ords, returning a referen'e to the ob*e't itself is safe in this 'ase. #he fun'tion 'all operator, properly kno)n as the appli'ation operator, /0, must be a member of the 'lass. &t 'an have any number of arguments. &n this example, it has *ust one3
dou(le CPoint::operator(# (const dou(le )# { dou(le &esult; &esult ),h + )+v; return &esult; :

#he unusual thing about this operator is that it 'an turn the ob*e't itself into something that looks like a fun'tion. #hus, in the 'lient program, )e 'an )rite
const CPoint &(2,3#; cout << "4alue of &(3# is " << &(3# << endl;

;ere, the expression, &(3# looks like a 'all to the fun'tion r )ith argument 3+ &n fa't it is a 'all to the (# operator of the ob*e't &. "

Software Design Lecture Notes Overloading Operators in C++

Prof. Stewart Weiss

Using friend operators <n alternative is to use a non-member fun'tion to implement an operator. #he non-member )ill have to be a friend if it needs a''ess to prote'ted or private data. &n the above example the stream insertion operator and the addition operator are non-members. #heir implementations follo)3
ost&eam$ operator<<(ost&eam$ out, CPoint$ P# { out << "(" << P+h << "," << P+v << "#"; &etu&n out; *

4oti'e that the return value of the insertion operator is a referen'e to a stream. #his is be'ause )hen something is )ritten to a stream, the stream itself is modified. #he pointer to the next point of )riting is advan'ed, among other things, so the stream must be passed as a referen'e result. &t must also appear as an argument so that it 'an be )ritten onto by the fun'tion. #he fun'tion is a non-member, so it is passed any ob*e't of the given 'lass as a parameter. #he addition operator is a simpler example of a friend. &t is given t)o arguments and returns in this 'ase an ob*e't of the same 'lass. &t de'lares a lo'al variable that must be returned by value, not referen'e.
CPoint operator+ (const CPoint$ lhs, const CPoint$ &hs# { CPoint &esult &hs; &esult+h lhs+h + &hs+h; &esult+v lhs+v + &hs+v; return &esult; *

Some Other Rules To Remember #here are a fe) things you must remember about overloading operators. (ome are )hat you might expe't, others perhaps not3 =ou 'annot 'hange the number of operands of an operator that you are overloading. +or example, if the standard operator has t)o operands, so must your overload. =ou 'an only overload operators that a't on 'lasses. &n other )ords, at least one of the operands must be an instan'e of a 'lass. =ou 'annot 'hange the pre'eden'e of an operator that you are overloading. =ou 'annot 'reate ne) operators by overloading other symbols.

Вам также может понравиться