In order to explicit type conversion operators and c++primer the different places in the book, and to provide more meaningful examples, the author spent a lot of thought, please be sure to understand carefully.
Type conversion operators
Look at the following example:
At this point, a primitive of a plural class defines a type conversion operator of type Double. Once you have it, you can use it like this:
The output results are as follows:
Complex does not support output operators, so the compiler attempts to convert C1 to a double type after output. It's been a good time so far.
do you really want to convert it into a double?
Then look at the following code:
If you are mathematically speaking, you should output 2.23606. But actually, this code doesn't even compile. The reason for this is that there are two options for this code compiler: one is to convert C1 to double and then add 1, and the other is to perform complex addition after converting 1 to a complex number (1+0i).
Need a programmer to give an idea.
Explicit type-conversion operators
One way to eliminate ambiguity is to use explicit to disallow implicit double-type conversions. The code is as follows:
Because implicit type conversions are not possible, the following code will have a compilation error:
This is not a big problem, because converting to double output is not a good thing to say. The output function of the complex is already available in the code through the export operator overloads.
The output is as follows:
That's what we really want!
Add a little
If you want, you can also encode:
Think this article is helpful? Please share to more people.