说说隐式转换
C++允许指定在类和其他类型之间进行转换的方式。任何接受唯一一个参数的构造函数都可被用作转换函数,可以将该构造函数参数类型的值转换为类对象。如果将构造函数参数类型的值赋给对象,C++自动调用该构造函数。假设有一个String类,它包含一个将char *值作为其唯一参数的构造函数,那么,如果bean是String对象,则可以使用下面的语句:
bean = “pinto”;
即将char* 转化为String。
然而,如果在构造函数的声明前加上了关键字explicit,则该构造函数只能用于显式转换。上面的语句需要写为以下形式:
bean = String("pinto");
举例说明(取自C++ primer plus 11.16,为描述简洁,删减了大部分代码)
class Stonewt
{
private:
enum { Lbs_per_stn = 14 }; // pounds per stone
double pounds; // entire weight in pounds
public:
Stonewt(double lbs); // constructor for double pounds
Stonewt(); // default constructor
void show_lbs() const; // show weight in pounds format
};
Stonewt::Stonewt(double lbs)
{
cout << "Constructor calls\n";
pounds = lbs;
}
Stonewt::Stonewt() // default constructor, wt = 0
{
pounds = 0;
}
// show weight in pounds
void Stonewt::show_lbs() const
{
cout << pounds << " pounds\n";
}
然后在main中做如下调用:
int main(int argc, _TCHAR* argv[])
{
Stonewt myCat;
Stonewt myDog(14.1);//调用构造函数
myCat = 13.6;//隐式转换,以另一种方式调用构造函数
myCat.show_lbs();
myDog.show_lbs();
return 0;
}
下面是函数的执行结果:
上面我用两种方式调用构造函数,一种是直接调用构造函数生成对象,另一种使用隐式转换。