Usage of explicit in C ++ Constructor

Source: Internet
Author: User

We are writing an application.ProgramWhen the explicit it keyword is rarely used, it is used to "prohibit Single-parameter constructor" is used for automatic type conversion.

Class Aclass
{
Public:
Explicit Aclass(Int I): M_ I (I ){/*...*/};
//...
};

Aclass A(1 );// OK
Aclass B=Static_cast<Aclass> (2 );// OK
// Aclass B = 2; // Error
// A = 3; // Error

When we use the followingCodeHour

Class C1 {
Public:
C1 (int ){....}
}
C1 myone;
Myone = 5; // copy constructor called

A temporary object temp (5) is generated first, and then the temporary object temp is assigned to myone by using the copy constructor.

When explicit it is added before the C1 constructor name, myone = 5 cannot be compiled, because only the constructor can be called to create objects.

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.