Explicit keywords in C + +

Source: Internet
Author: User

The explicit keyword is in C + + to prevent an implicit conversion

(1)

Explicit

This keyword can only work on the user's own defined object, not the default constructor
This keyword can only decorate constructors. And the constructor parameter can only have one:

(2) When to use explicit

When we do not want to use the automatic type conversion, in fact, the standard library a lot of constructors are explicit

such as vectors <int> Ivec (10); This definition looks at a glance

cannot be written as vector <int> ivec=10;//This definition makes the programmer wonder

(3) when not to explicit

When we need an implicit conversion,

For example, a constructor for a string class

String (const char*);

This is defined as the benefit of the compiler automatically helping us to convert when implicit conversions are required, and the string in the standard library is a good proof.

Specifically:

We can do this by string str= "HelloWorld";//Call constructor directly

String str= "Hello" +str+ "world";

Call the overloaded + action symbol, which is equivalent to:
String temp ("Hello"); Call constructor

String Str=temp+str;

String T ("World");//Call constructor

String str=str+t;

It is useful to understand implicit conversions when we write our own classes, especially when manipulating memory classes.

Explicit keywords in C + +

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.