转换构造函数定义了类的隐式转换规则,此构造函数只接受一个实参。可以从该参数类型转换为类类型。
Sales_data(const std::string &s) : bookNo(s), units_sold(0), revenue(0.0) { } Sales_data::Sales_data(std::istream &is) { // read will read a transaction from is into this object read(is, *this); }通过上面两个构造函数,定义了从string类型和istream类型到Sales_data类型的转换。
string null_book = "999"; // 构造一个临时的Sales_data对象 // 对象的其他成员变量都为0,bookNo等于999 item.combine(null_book); item.combine(cin); // 通过istream构造一个零时对象为了抑制构造函数定义的隐式转换,可以将构造函数声明为explicit:
explicit Sales_data(const std::string &s) : bookNo(s), units_sold(0), revenue(0.0) { } explicit Sales_data::Sales_data(std::istream &is);关键字explicit只对一个实参的构造函数有效。需要多个实参的构造函数不能用于执行隐式转换,所以无需指定。 声明为explicit的构造函数只能用于直接初始化。