C ++ modifies the explicit keyword of the constrstructor.

Source: Internet
Author: User

The C ++ explicit keyword is mainly used to modify the class constructor, indicating that the constructor is explicit and the implicit conversion of a single parameter constructor is prohibited.

If the constructor of the C ++ class has a parameter, a default conversion operation will be performed during compilation: Convert the data of the corresponding data type of the constructor to this type of object, as shown below:

Class myclass

{

Public:

Myclass (INT num );

}

Myclass OBJ = 10; // OK, convert int to myclass

The aboveCodeThe compiler automatically converts an integer to a myclass object, which is actually equivalent to the following operation:

Myclass temp (10 );

Myclass OBJ = temp;

All the above operations are called "implicit conversions ".

To avoid this automatic conversion function, you can add the explicit keyword before declaring the constructor and declare the constructor of the class as "display ", this will prevent this automatic conversion operation.

Modify the constructor of the above myclass class as shown in. The following Code cannot be compiled as follows:

Class myclass

{

Public:

Explicit myclass (INT num );

}

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.