C++primer plus第六版课后编程题答案11.6

stonwth.h

#ifndef STONEWT_h_
#define STONEWT_h_
#include <iostream>
using namespace std;
enum Mode{STONE,POUNDS};//方便main115,cpp
class Stonewth
{
private:
	
	enum {Lbs_per_stn=14};
	Mode mode;
	int stone;
	double pds_left;
	double pounds;
public:
	Stonewth(double lbs)
	{
		mode=POUNDS;//用于控制输出什么格式
		stone=int(lbs)/Lbs_per_stn;
		pds_left=int(lbs)%Lbs_per_stn+lbs-int(lbs);
		pounds=lbs;
	};
	Stonewth(){
		mode=POUNDS;//默认为镑
		stone=pds_left=pounds=0;
	};
	Stonewth(int stn,double lbs)
	{
		mode=POUNDS;
		stone=stn;
		pds_left=lbs;
		pounds=stn*Lbs_per_stn+lbs;
	};
	void setMode(Mode form=STONE)
	{
		if(form==STONE)
			mode=STONE;
		else if(form==POUNDS)
			mode=POUNDS;
		else
			cout<<"Invail mode !"<<endl;
	}
	Stonewth operator+(const Stonewth &s)const//这里我就选最简单的了
	{
		double newpounds=pounds+s.pounds;
		return Stonewth(newpounds);
	}
	Stonewth operator-(const Stonewth &s)const
	{
		double newpounds=pounds-s.pounds;
		return Stonewth(newpounds);
	}
	Stonewth operator*(double m)const//我这里选择重载常数*
	{
		double newpounds=pounds*m;
		return Stonewth(newpounds);
	}
	//11.6
	bool operator<(const Stonewth &s)
	{
		return pounds>s.pounds;
	}
	bool operator>(const Stonewth &s)
	{
		return s.pounds<pounds;
	}



	friend ostream& operator<<(ostream &os,const Stonewth &s)
	{
		if(s.mode==STONE)
			os<<s.stone<<"  stone!"<<endl;
		else if(s.mode==POUNDS)
			os<<s.pounds+s.pds_left<<"  pounds!"<<endl;
		else
			os<<"error!"<<endl;
		return os;
	}



};
#endif

main116.cpp

#include <iostream>
#include "stonewt.h"
using namespace std;
void main116()
{
	Stonewth s[6]={10,9.5,19};
	//Stonewth s1=10;
	//cout<<s1<<endl;
	Stonewth temp(11);
	for(int i=0;i<3;i++)
		cout<<s[i]<<endl;
	for(int i=3;i<6;i++)
	{
		cout<<"enter the pounds:"<<endl;
		double in;
		cin>>in;
		s[i]=in;
	}
	//没有重载=,懒得重载了,这里会有点问题,自己改下
	Stonewth max=-999;
	Stonewth min=999;
	for(int i=0;i<6;i++)
	{
		if(max<s[i])
			max=s[i];
		if(min>s[i])
			min=s[i];
		if(s[i]>temp)
			cout<<s[i]<<endl;
	}

	cout<<"max="<<max<<"   min="<<min<<endl;
	cin.get();
	cin.get();

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值