C++PrimerPlus第十一章类的使用,程序清单11.16,11.17,11.18类自动类型转换和强制类型转换(重量单位:英石和磅的转换)0001

数可以进行类型隐式类型转换和强制类型转换
类能不能支持这种呢,正常是不支持的,但是可以通过构造函数将问题转换为,基本数据类型的隐式转换或强制类型转换

//stonewt.h  -- definition for the stonewt class
#ifndef STONEWT_H_
#define STONEWT_H_
class Stonewt
{
private:
	enum {Lbs_per_stn = 14};	//pouns per stone 转换因子
	int stone;					//whole stone  英石 
	double pds_left;			//fractional pounds
	double pounds;				//entire weight in pounds 磅

public:
	Stonewt(double lbs);			//constructor for double pounds
	Stonewt(int stn, double lbs);	//constructor for stone,lbs
	Stonewt();						//default constructor 
	~Stonewt();
	void show_lbs()const;			//show weight in pounds format
	void show_stn()const;			//show weight in stone format
};


#endif // !STONEWT_H_
//stonewt.cpp -- Stonewt methods
#include<iostream>
#include"stonewt.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";
}
#pragma region 11.18.stone.cpp
程序清单
//stone.cpp -- user-defined conversions
#if 1
#include <iostream>
#include"stonewt.h"
using std::cout;
void display(const Stonewt& st, int n);
int main()
{
	Stonewt incognito = 275;//uses constructor to initialize
	Stonewt wolfe(285.7);//same as Stonewt wolfe = 285.7
	Stonewt taft(21, 8);

	cout << "The celebrity weighed ";
	incognito.show_stn();
	cout << "The detective weighed ";
	wolfe.show_stn();
	cout << "The President weighed ";
	taft.show_lbs();
	incognito = 276.8;
	taft = 325;

	cout << "After dinner,the clelbrity weighed ";
	incognito.show_stn();
	cout << "After dinner,the President weighed ";
	taft.show_lbs();
	display(taft, 2);
	cout << "The wrestler weighed even more.\n";
	display(422, 2);
	cout << "No stone left unearned\n";
	return 0;
}
void display(const Stonewt& st, int n)
{
	int i;
	for ( i = 0; i < n; i++)
	{
		cout << "Wow! ";
		st.show_stn();
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值