C++隐式转换

说说隐式转换

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;
}

下面是函数的执行结果:

上面我用两种方式调用构造函数,一种是直接调用构造函数生成对象,另一种使用隐式转换。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值