How to apply C + + explicit keywords

Source: Internet
Author: User

Many of the more important keywords in the C + + programming language play a very important role in practical programming. The C + + explicit keyword We've introduced to you today is one of the more frequently used keywords. Let's take a look at this knowledge together.

C + + Explicit keyword is used to decorate the constructor of the class, indicating that the constructor is explicit, since there is "explicit" then there must be "implicit", then what is the display and what is implicit?

If the constructor of a C + + class has a parameter, there is a default conversion operation at compile time: Convert the data of that constructor's data type to that class object, as shown here:

    1. Class MyClass
    2. {
    3. Public
    4. MyClass (int num);
    5. }
    6. //.
    7. MyClass obj = ten;//ok,convert int to MyClass

In the code above, the compiler automatically converts an integral type to an MyClass class object, which is actually equivalent to the following operation:

    1. MyClass Temp (10);
    2. MyClass obj = temp;

All of the above-mentioned C + + explicit keyword-related operations are called "implicit conversions."

What do we do if we want to avoid this kind of auto-conversion function? Hey, this is the keyword explicit, the constructor of the class is declared as "explicit", that is, when declaring the constructor is added before the explicit can be prevented, so as to prevent this automatic conversion operation, if we modify the above MyClass class constructor is explicit, Then the following code will not be able to compile through, as follows:

    1. Class MyClass
    2. {
    3. Public
    4. explicit MyClass (int num);
    5. }
    6. //.
    7. MyClass obj = ten;//err,can ' t non-explict convert

This article transferred from: http://developer.51cto.com/art/201002/183398.htm

How to apply C + + explicit keywords

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.