The explicit in C + +

Source: Internet
Author: User

Explicit: detailed, clear, explicit, undisguised, explicit, external, clear, straightforward, (rent, etc) direct payment.

In C + +, a constructor of a parameter (or a multiple-parameter constructor with a default value except for the first argument) takes two roles. 1 is a constructor, and 2 is a default and implied type conversion operator. So, sometimes when we write code such as AAA = XXX, and exactly the type of XXX is the parameter type of the AAA single parameter constructor, the compiler automatically invokes the constructor and creates a AAA object. This looks like a cool, very convenient. But in some cases (see the authoritative example below), it violates our (Programmer's) intent. This is the time to add a explicit modifier to the constructor, specifying that the constructor can be invoked only explicitly, and cannot be used implicitly as a type conversion operator. Oh, it seems to be aboveboard some better. Explicit constructor function resolution: Explicit constructors are used to prevent implicit conversions. Take a look at the following code:

Class Test1
{public
:
    Test1 (int n) {num = n;}//Normal constructor
private:
    int num;
};
Class Test2
{public
:
    explicit Test2 (int n) {num = n;}//explicit (Explicit) constructor
private:
    int num;
};
int main ()
{
    Test1 t1 = 12;//implicitly calls its constructor, succeeds
    Test2 t2 = 12;//Compilation error, cannot implicitly call its constructor
    Test2 T3 (12); 18/>return 0;
}


The Test1 constructor takes an int parameter, and the code 17 line is implicitly converted to this constructor that calls Test1. The Test2 constructor is declared as explicit (explicit), which means that the constructor cannot be invoked through an implicit conversion, so there is a compilation error in the code 18 line. An ordinary constructor can be called implicitly. The explicit constructor can only be displayed for invocation.

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.