C++隐式类类型转换
《C++ Primer》中7.5.4提到:“能通过一个实参调用的构造函数定义了一条从构造函数的参数类型向类类型隐式转换的规制。”
"能通过一个实参调用的构造函数"不是特指只有一个形参的构造函数,它可以有多个形参,但那些形参都是有默认值的。
#include <string>
#include <iostream>
using namespace std;
struct Sales_data
{
string bookNo;
unsigned units_sold;
double revenue;
Sales_data() = default;
Sales_data(const string &s, unsigned n=1, double p=1.5f):bookNo(s), units_sold(n), revenue(p*n){}
string combin(const Sales_data &);
};
string Sales_data::combin(Sales_data &that)
{
units_sold = that.units_sold;
revenue = that.revenue;
return that.bookNo;
}
int main()
{
Sales_data A("A");
Sales_data B("B");
cout << A.combin(B) << endl;
cout << A.combin(string("C")) << endl;
cout << A.combin(Sales_data("D")) << endl;
return 0;
}
A.combin(string(“C”)) 发生一个隐式转换:string类型到Sales_data类型,借助Sales_data的构造函数进行转换,以满足combin函数的参数期待。
隐式类类型转换还是会带来风险的,隐式转换得到类的临时变量,完成操作后就消失了,因此我们可以通过explicit声明来抑制这种隐式转换。
struct Sales_data
{
explicit Sales_data(const string &s, unsigned n=1, double p=1.5f):bookNo(s), units_sold(n), revenue(p*n){}
// 其余的代码一样
};