Content deleted Content added
HHWhitePony (talk | contribs) m Fixing →Overloading Operators |
Fix spelling using AWB |
||
Line 4:
For example, ''doTask()'' and ''doTask(object O)'' are '''overloaded''' methods. To call the latter, an [[Object (computer science)|object]] must be passed as a [[parameter]], whereas the former does not require a parameter, and is called with an empty parameter field.
A common error would be to assign a default value to the object in the second method, this would result in an ''ambiguous call'' error, as the compiler wouldn't know
Another example would be a ''Print(object O)'' method. In this case we would like the method to be different when printing, for example, text and different for pictures. We write the two different methods as overloaded: ''Print(text_object T); Print(image_object P)''. If we write the overloaded print methods for all objects our program will "print", we never have to worry about the type of the object, and the correct [[subroutine|function]] call again, the call is always: ''Print(something)''.
Line 30:
}
Addition is a [[binary operation|binary]] operation, which means it has a left and right [[operand]]. In C++, the ''temp'' object in this case is the left operand and the arguments being passed are the right operands. Note that a [[unary operation|unary]] operator would
The [[compiler]] would be able to differentiate the two addition operators because one is passed three parameters instead of the normal addition which is passed just one. As mentioned above however, methods are overloaded based on their number AND type of parameters.
Another overloaded addition operator could be overloaded with three parameters IF the data types passed are different too. The compiler would differentiate those two by their data types. The following shows how it would be setup using an [[angle]] as a data type with [[
Angle Angle::Operator+(double Degree, double Minutes, double Seconds)
Line 52:
The drawback to this is that is takes two steps to change the value of the created Bill object. The following shows creation and changing the values within the main program:
Bill cafe;
cafe.tip = 10.00;
|