Some built-in types of the C + + language can be converted automatically, and class types are also available. Typically, a constructor that passes a single argument defines an implicit conversion from the formal parameter to the class type.
For example, we define a class
Class Sales_item {public:sales_item (const std::string &book = ""): ISBN (Book), Units_sold (0), Revenue (0.0) {}sales_ Item (Str::istream &is);p rivate:string isbn;int units_sold;double revenue;};
The two constructors here have only one parameter, so implicit conversions are possible. That is, in a place where you expect to pass a Sales_item type object, you can pass a string or istream that can be implicitly converted to the Sales_item class object. Like what:
A member function of the bool SAME_ISBN (Sales_item) {} //sales_tiem Sales_item item; Defines an object string null_book = "9-999-99999-9"; Item.same_isbn (Null_book);
When you call ITEM.SAME_ISBN (Null_book), you actually pass a constructor that executes the
Sales_item (Null_book)
Object, that is, a string of type Null_book implicitly converted to Sales_item.
We need to understand the nature of this implicit conversion of constructors in order to write out the programs that we want to implement for a particular function without any puzzling bugs. For me now, it is not good to judge whether implicit conversions of class types are needed in the actual development process, and if it is not necessary to avoid implicit conversions, we need to know how to suppress implicit conversions.
We only need to use the explicit keyword to print its implicit conversions on the declared constructor.
Explicit Sales_item (const std::string &book = ""): ISBN (Book), Units_sold (0), Revenue (0.0) {}explicit Sales_item (str :: IStream &is);
It is important to note that the explicit keyword decoration is required only within the class, and when the definition of the constructor is outside the class, there is no need to use explicit, in fact, if you use explicit outside of the class, you will get an error.
After this is declared, we pass the string type argument again
will be an error.
Of course, we can display the call constructor.
ITEM.SAME_ISBN (Sales_item (Null_book));
Implicit class-Type conversions