C++PrimerPlus第十一章类的使用,类自动类型转换和强制类型转换(重量单位:英石和磅的转换)0003

程序清单 11.21对新的转换函数进行测试。该程序中的赋值语句使用隐式转换,而最后的cout 语句使用显式强制类型转换。请务必将程序清单 11.20与程序清单11.21一起编译。

//stonewt.cpp -- Stonewt methods
#include<iostream>
#include"stonewt1.h"
using std::cout;

//construct Stonewt object from double value
Stonewt::Stonewt(double lbs)
{
	stone = int(lbs) / Lbs_per_stn;//integer division
	pds_left = int(lbs) % Lbs_per_stn + lbs - int(lbs);
	pounds = lbs;
}


//construct Stonewt object from stone,double values
Stonewt::Stonewt(int stn, double lbs)
{
	stone = stn;
	pds_left = lbs;
	pounds = stn * Lbs_per_stn + lbs;
}


//default construct Stonewt wt = 0
Stonewt::Stonewt()
{
	stone = pounds = pds_left = 0;
}

//destructor
Stonewt::~Stonewt()
{

}

//show weight in stones
void Stonewt::show_stn()const
{
	cout << stone << " stone, " << pds_left << " pounds\n";
}

//show weight in pounds
void Stonewt::show_lbs()const
{
	cout << pounds << " pounds\n";
}

//conversion functions 
Stonewt::operator int()const
{
	return int(pounds + 0.5);
}

Stonewt::operator double()const
{
	return pounds;
}

下面引出测试函数,下一个文件中测试,这样分开方便阅读,有的小伙伴看到内容太多,都吓到了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值