By using the keyword "Explicit", I can disable "Single-parameter constructor" from being used for automatic type conversion.
A typical example is the cluster type. You can pass the initial length as a parameter to the constructor. For example
Class P
{
Public:
Explicit P (int x): Y (x), STR ("ssss ")
{
Cout <STR <Endl;
}
P (const P & D)
{
Y = D. Y;
STR = new char [strlen (D. Str) + 1];
If (D. Str)
Strcpy (STR, D. Str );
Else
Cout <"empty" <Endl;
}
Virtual void g ()
{
Cout <"P virtual function" <Endl;
Cout <STR <Endl;
}
PRIVATE:
Int y;
Char * STR;
};
Void main ()
{
P t = 5; // Error
P t (5 );
}
At this time, the compiler will report the following error: Error c2440: 'initializing': cannot convert from 'const int' to 'class P'
The "automatic type conversion" Action converts 5 to the p type containing five elements and assigns it to T. This is incorrect.
If no explicit it is added before the constructor, the p t = 5 compiler will not report an error, which causes a risk. Therefore, it is best to add the explicit it before the constructor.