C++11 Common Syntax-explicit type conversion operator specific usage

Source: Internet
Author: User
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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.