[C++ Primer Chapter 7] Implicit class type conversion

conversion constructor

Converting constructors : If a constructor accepts only one argument, it actually defines an implicit conversion mechanism that converts such types, sometimes we call such constructors converting constructors.

A constructor that can be called with an argument defines a rule for implicit conversion from the constructor's parameter type to the class type.

For example, in the Sales_data class, the constructor that accepts string and the constructor that accepts istream respectively define the rules for implicit conversion from these two types to Sales_data. That is, where we need to use Sales_data, we can use string or istream instead:

Constructor:
Sales_data(const string &s);
Sales_data(istream &);
Sales_data &combine(const Sales_data&);

string null_book="9-999-99999-9";
item.combine(null_book); // Construct a temporary Sales_data object
                          // The units_sold and revenue of this object are equal to 0, and bookNo is equal to null_book

Here we call the combine member of Sales_data with a string argument. This call is valid, the compiler automatically creates a Sales_data object with the given string. This newly generated (temporary) Sales_data object is passed to combine. Because the parameter of combine is a constant reference, we can pass a temporary to the parameter .

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324646907&siteId=291194637