|
|
 |
|
|
|
|
35: varThree = varOne + varTwo;
36: cout << varOne: << varOne.GetItsVal()<< endl;
37: cout << varTwo: << varTwo.GetItsVal() << endl;
38: cout << varThree: << varThree.GetItsVal() << endl;
39:
40: return 0;
41: } |
|
|
|
|
|
|
|
|
varOne: 2
varTwo: 4
varThree: 6 |
|
|
|
|
|
|
|
|
Analysis: operator+ is declared on line 14 and defined on lines 2730. Compare these with the declaration and definition of the Add() function in the previous listing; they are nearly identical. The syntax of their use, however, is quite different. It is more natural to say this: |
|
|
|
|
|
|
|
|
varThree = varOne + varTwo; |
|
|
|
|
|
|
|
|
varThree = varOne.Add(varTwo); |
|
|
|
|
|
|
|
|
Not a big change, but enough to make the program easier to use and understand. |
|
|
|
|
|
|
|
|
Limitations on Operator Overloading |
|
|
|
|
|
|
|
|
New Term: Operators on built-in types (such as int) cannot be overloaded. The precedence order cannot be changed, and the arity of the operator, that is whether it is unary or binary, cannot be changed. You cannot make up new operators, so you cannot declare ** to be the power of operator. |
|
|
|
|
|
|
|
|
Operator overloading is one of the aspects of C++ most overused and abused by new programmers. It is tempting to create new and interesting uses for some of the more obscure operators, but these invariably lead to code that is confusing and difficult to read. |
|
|
|
|
|
|
|
|
Of course, making the + operator subtract and the * operator add can be fun, but no professional programmer would do that. The greater danger lies in the well-intentioned but idiosyncratic use of an operatorusing + to mean concatenate a series of letters, or / to mean split a string. There is good reason to consider these uses, but there is even better reason to proceed with caution. Remember, the goal of overloading operators is to increase usability and understanding. |
|
|
|
|
|