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.