What is the difference between explicit and implicit?

Source: Internet
Author: User

Before figuring out the differences between the two keywords, you need to figure out another Keyword: operator.

Operator msdn explanation:

UseOperatorKeyword to overload the built-in operators, or provide user-defined conversions in the class or structure declaration.

That is to say: operator has two functions: 1) Operator Overloading 2) Conversion of user-defined classes, that is, operator conversion.

Here we only talk about operator conversion. For example, I have defined the following class (the code is from msdn)

 

Class Digit

{

Public digit (double D) {val = D ;}

Public double val;

//... Other members

 

}

 

If I want to convert the digit class to the dobule type, that is

Digit dig = 12; certainly, an error is reported because conversion from double to digit is not defined here. It is defined as follows:

 

Class Digit

{

Public digit (double D) {val = D ;}

Public double val;

//... Other members

 

// User-Defined conversion from digit to double

Public Static Implicit operator double (digit D)

{

Return D. Val;

}

// User-Defined conversion from double to Digit

Public Static Implicit operator digit (double D)

{

Return new digit (d );

}

 

}

No error will be reported, because the conversion from double to digit operator is defined here:

Public Static Implicit operator digit (double D)

 

 

{

Return new digit (d );

}

In turn, explicit and implicit

Explicit is the type conversion of the display. If the double operator is defined in this way

// User-Defined conversion from digit to double

Public static explicit operator double (digit D)

{

Return D. Val;

}

 

 

Double num = dig.

Convert a digit type to a double type

 

 

Double num = (double) Dig;

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.