Meaning and usage of C ++ explicit

Source: Internet
Author: User

Explicit is used to modify the class constructor, indicating that the constructor is explicit,

 

It is a default constructor used for user-defined constructor and cannot be used to convert constructor. Because there are three constructor types, 1 copy constructor 2 convert constructor 3 Constructor

When a class has multiple constructors, the constructor modified by explicit is the default one.

Class string {

PRIVATE:

Int size;

Int capacity;

Char * Buff;

Public:

String ();

String (INT size );

String (const char *);

~ String ();

};

 

Int main (){

String S = "hello ";

Int NS = 0;

S = 1;

}

S = 1. I originally thought NS = 1, but I wrote an error and wrote it as S = 1, because there is a constructor that accepts an int type parameter, so we will try to use string (1)

To avoid similar errors, we add the explicit keyword to the front,

Explicit string (INT size)

 

A good example:

Class People {

Public:

Int age;

Explicit people (int ){

Age =;

}

};

Void Foo (void ){

People p1 (10); // method 1

People * p_p2 = new people (10 );

People P3 = 10; // method 3. An error is returned. If explicit it is removed, no error is returned.

}

Gcc-s people. cpp

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.