程序清单 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;
}
下面引出测试函数,下一个文件中测试,这样分开方便阅读,有的小伙伴看到内容太多,都吓到了。

被折叠的 条评论
为什么被折叠?



