C ++ keyword explicit

Source: Internet
Author: User

The explanation of explicit is as follows:;Clear;Clear. So what does explicit it mean in C ++?

Explicit (displayed)

(1) Explicit can disable "Single-parameter constructor" from being used for automatic type conversion, effectively preventing errors caused by implicit conversion of constructor.

(2) explicit only applies to constructors and is used to suppress implicit conversions.

(3) All single-parameter constructors must be explicit to avoid type conversion in the background.

Use an instance to describe the above two points:

# Include <iostream>
Using NamespaceSTD;

ClassPeople
{
Public:
People (IntAge ){}
People (StringName ){This-> Name = Name ;}
IntAge;
StringName;
};

IntMain ()
{
People people1 (25);
People people2 =25;

Return 0;
}

The above compilation of people people2 = 25 is actually able to pass, and 25 is assigned to people, which is a bit difficult to say. To avoid this, you need to add the keyword "Explicit" to the constructor,ProgramAs follows:

 

# Include <iostream>
Using Namespace STD;

Class People
{
Public :
Explicit People ( Int Age ){}
People ( String Name ){ This -> Name = Name ;}
Int Age;
String Name;
};

Int Main ()
{
People people1 ( 25 );
// People le2 = 25; // Error c2440: 'initializing': cannot convert from 'const int' to 'class people'

Return 0 ;
}

after the keyword "Explicit" is added, people le2 = 25 cannot be compiled.

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.