The use and detailed explanation of c++:explicit in the construction function

Source: Internet
Author: User

The main use of explicit is to put in a single parameter constructor, to prevent implicit conversion, resulting in the function of the entry parameters, there is ambiguity.

If you can use a construct B, an explicit constructor, when you use B for parameter processing, you can use a to make the interface confusing.

To avoid this, use explicit to avoid implicit constructs, only by displaying (explicit) constructs.

Here is the code, read carefully must be harvested, you can try to delete explicit, call the comment statement.

/************************************************* File:main.cpp Copyright:c.l.wang Author:c.l.wang date:2014-04-  Description:explicit email:morndragon@126.com **************************************************//*eclipse  
      
CDT, gcc 4.8.1*/#include <iostream> using namespace std;  
      
Class A {}; Class B {public://Conversion from A (constructor): explicit B (const a& x) {std::cout <<  
  B ' s constructor << Std::endl; }//Conversion from A (Assignment): b& operator= (const a& x) {std::cout << "B" as  
      Signment "<< Std::endl;  
  return *this; }//Conversion to a (type-cast operator) operator A () {std::cout << "B ' s Conversion" &LT;&L T  
      Std::endl;  
  return A ();  
      
}  
};  
VOID fn (B arg) {std::cout << "function" << Std::endl;  
  int main () {A foo; B Bar (foo);    B bar = foo;      Calls constructor, add explicit error, cannot default construction//bar = foo;      Calls assignment//foo = bar; Calls Type-cast operator//FN (foo);  
      
  Error adding explicit, you cannot implicitly convert fn (bar) by default;  
return 0; }

Output:

B ' s constructor  
function

Author: csdn Blog spike_king

More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/cplus/

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.