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" <&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/