11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

306Part V: Optional FeaturesC++ gives each operator a function-style name. The functional name of anoperator is the operator symbol preceded by the keyword operator and followedby the appropriate argument types. For example, the + operator thatadds an int to an int generating an int is called int operator+(int, int).Any operator can be defined for a user-defined class. Thus, I could create aComplex operator*(Complex&, Complex&) that would allow me to multiplytwo objects of type Complex. The new operator may have the samesemantics as the operator it overloads, but it doesn’t have to. The followingrules apply when overloading operators: The programmer cannot overload the ., ::, * (dereference), and &operators. The programmer cannot invent new operators. You cannot invent theoperation x $y. The format of the operators cannot be changed. Thus, you cannot definean operation %i because % is a binary operator. The operator precedence cannot change. A program cannot forceoperator+ to be evaluated before operator*. The operators cannot be redefined when applied to intrinsic types —you can’t change the meaning of 1 + 2. Existing operators can be overloadedonly for newly defined types.Overloading operators is one of those things that seems like a much betteridea than it really is. In my experience, operator overloading introduces moreproblems than it solves, with two notable exceptions that are the subject ofthis chapter.Inserting a New OperatorThe insertion and extraction operators > are nothing more than theleft and right shift operators overloaded for a set of input/output classes.These definitions are found in the include file iostream (which is whyevery program includes that file). Thus, cout

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!