C + + explict__c++

Source: Internet
Author: User

C + + Explicit keyword is mainly used to modify the class's constructor, indicating that the constructor is explicit, prohibiting the implicit conversion of single parameter constructors.

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

Class MyClass

{

Public

MyClass (int num);

}

MyClass obj = 10; OK, convert int to MyClass

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

MyClass Temp (10);

MyClass obj = temp;

All of the above actions are called "implicit conversions".

If you want to avoid this automatic conversion function, you can prevent this automatic conversion operation by adding the EXPLICT keyword before declaring the constructor and declaring the class's constructor as "display".

To modify the constructor of the above MyClass class for display, the following code will not be able to compile through, as follows:

Class MyClass

{

Public

explicit MyClass (int num);

}

MyClass obj = 10; Err,can ' t non-explict convert

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.