To understand how to overload operators, that 's useful to think about what happens when the compiler encounters an operator. Using the addition operator (+) as an example, suppose that compiler processes the following lines of code:
int myInteger = 3;
uint myUnsignedInt = 2;
double myDouble = 4.0;
long myLong = myInteger + myUnsignedInt;
double myOtherDouble = myDouble + myInteger;
What happens when the compiler encounters the following line?
long myLong = myInteger + myUnsignedInt;
The compiler determines that it is necessary to add two integers and assign the result to long. However, the + myUnsignedInt myInteger expression is really just a syntax intuitive and convenient to call a method that adds two numbers. The method takes two parameters, and myInteger myUnsignedInt, and returns their sum. Therefore, the compiler does the same as you would for any
method call - that seeks the best possible overload the addition operator based on the parameter types - in this case, which takes two integers. As with the normal methods of overloading, the desired performance type is irrelevant to the compiler 's ability to choose which version of a method call. As it happens, the
call overhead in the example takes two int parameters and returns an int, the return value is subsequently becomes a long term.
The next line causes the compiler to use a different overload of the addition operator:
double myOtherDouble = myDouble + myInteger;
In this case, the parameters are a double and an int, but there is an overload of the addition operator that has this combination of parameters. Instead, the compiler identifies the best game overloading the addition operator as is the version that takes two double s and their parameters, and implicitly casts the int to a double. The addition of two double s requires a different process of adding two integers. Floating - point numbers are stored as a mantissa and an exponent. Adding them is in bits -- shifting the mantissa of one of the two s for the two exponents have the same value, adding that the mantissas, then change the mantissa of the results and adjust the exponent to maintain the highest
precise response.
Now, you are in a position to see what happens if the compiler finds something like this:
Vector vect1, vect2, vect3;
// initialize vect1 and vect2
vect3 = vect1 + vect2;
vect1 = vect1*2;
0 comments:
Post a Comment