Home >Backend Development >C#.Net Tutorial >C++11 common syntax - specific usage of explicit type conversion operator
In order to think about the differences between the explicit type conversion operator and the C Primer book, and provide more meaningful examples, the author has spent a lot of thought, so please understand it carefully.
Type conversion operator
Look at the following example:
At this time, the prototype of a plural class, Defines a type conversion operator for double type. After you have it, you can use it like this:
##The output result is as follows: complex is not The output operator is supported, so the compiler strives to convert c1 into a double type and then output it. So far so good.Do you really want to convert to double?
Look at the following code again: If from mathematics From a perspective, it should output 2.23606. But in fact, this code cannot even compile. The reason is that the compiler has two options for this code: one is to convert c1 to double and then add 1; the other is to convert 1 to a complex number (1 0i) and then perform complex addition. Need the programmer to give me an idea.Explicit type conversion operator
In order to eliminate ambiguity, one way is to use explicit to prohibit implicit double type conversion. The code is as follows: Since implicit type conversion cannot be performed, a compilation error will occur in the following code:This is not a big problem, because it is difficult to say whether converting to double output is correct or not. The code has provided the output function of plural form through the output operator overloading. The output is as follows: This is what we really want!
Additional point
If you like, you can also encode it like this: Find this article helpful? Please share it with more people. Related recommendations:HTML operators, type conversion
C# Custom implicit and explicit conversion
The above is the detailed content of C++11 common syntax - specific usage of explicit type conversion operator. For more information, please follow other related articles on the PHP Chinese website!