The explicit keyword in C + + is used to modify the constructor of the class, indicating that the constructor is explicit, and since there is "explicit" then there must be "implicit", so what is the display and what is implicit?
If the C + + class constructor has a parameter, then there is a default conversion operation at compile time: Converts the data of the constructor's corresponding data type to that class object, as shown here:
class MyClass
{
public:
MyClass( int num );
}
....
MyClass obj = 10; //ok,convert int to MyClass
In the code above, the compiler automatically converts an integer to the MyClass class object, which is actually equivalent to the following operation:
MyClass Temp (10);
MyClass obj = temp;
All of the above actions are called "implicit conversions".
What should we do if we want to avoid this automatic conversion function? Hey, this is the role of the keyword explicit, the constructor of the class declared as "display", that is, in the declaration of the constructor before the explicit can be added to prevent this automatic conversion operations, if we modify the above MyClass class constructor for display, The following code cannot be compiled, as follows:
Class MyClass
{
Public
explicit MyClass (int num);
}
....
MyClass obj = 10; Err,can ' t non-explict convert
Class Isbn_mismatch:public std::logic_error{
Public
Explicit Isbn_missmatch (const std::string &s): Std:logic_error (s) {}
Isbn_mismatch (const std::string &s,const std::string &lhs,const std::string):
Std::logic_error (s), left (LHS), right (RHS) {}
Const std::string Left,right;
Virtual ~isbn_mismatch () throw () {}
};
sales_item& operator+ (const sales_item &lhs,const sales_item RHS)
{
if (!LHS.SAME_ISBN (RHS))
Throw Isbn_mismatch ("ISBN missmatch", Lhs.book (), Rhs.book ());
Sales_item ret (LHS);
RET+RHS;
return ret;
}
Sales_item item1,item2,sum;
while (CIN>>ITEM1>>ITEM2)
{
try{
SUN=ITEM1+ITEM2;
}catch (const Isbn_mismatch &e)
{
Cerr<<e.what () << "left ISBN?:" <<e.left<< Right ISBN is: "<<e.right<<endl;
}
}