C ++ explicit keywords

Source: Internet
Author: User

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.

Related Article

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.