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


 

 

tv.h

#ifndef TV_h_
#define TV_h_
#include <iostream>
using namespace std;
class Remote;
class Tv{
private:
	int state;
	int volume;
	int maxchannel;
	int channel;
	int mode;
	int input;
public:
	friend class Remote;
	enum{Off,On};
	enum {MinVal,MaxVal=20};
	enum{Antenna,Cable};
	enum {TV,DVD};
	
	Tv(int s=Off,int mc=125):state(s),volume(5),maxchannel(mc),channel(2),mode(Cable),input(TV){};
	void onoff(){
		state=(state==On)?Off:On;
	};
	bool ison(){
		return state==On;
	};
	bool volup();
	bool voldown();
	void chanup();
	void chandown();
	void set_mode(){
		mode=(mode==Antenna)?Cable:Antenna;
	};
	void set_input(){
	
		input=(input==TV)?DVD:TV;	//这是个什么情况???
	};
	void setting()const;
	void setR(Remote &r);//这里不能有方法的定义,否则会导致前置声明的混乱而无法编译



};
class Remote
{
	friend class Tv;
private:
	int mode;
	int RemoteMode;//用于描述遥控器的模式
	enum{RemoteOn,RemoteOff};
public:
	Remote(int m=Tv::TV,int rm=RemoteOn):mode(m){};//构造函数多了一个
	bool volup(Tv &t){return t.volup();};
	bool vodown(Tv &t){ return t.voldown();};
	void onoff(Tv &t){return t.onoff();};
	void chanup(Tv &t){t.chanup();};
	void chandown(Tv &t){t.chandown();};
	void set_chan(Tv &t,int c){t.channel=c;};
	void set_mode(Tv &t){t.set_mode();}
	void set_input(Tv &t){t.set_input();};
	void show()
	{
		cout<<"RemoteMode:"<<(RemoteMode==RemoteOn?"RemoteOn":"RemoteOff")<<endl;
	}
	void change()
	{
		RemoteMode=RemoteOn?RemoteOff:RemoteOn;//用于Tv类切换
	}
};
#endif

tv.cpp

#include "tv.h"
#include <iostream>
using namespace std;

//tv
bool Tv::volup()
{
	if(volume<MaxVal)
	{
		volume++;
		return true;
	}
	else
		return false;
}

bool Tv::voldown()
{
	if(volume>MinVal)
	{
		volume--;
		return true;
	}
	else
		return false;
}

void Tv::chanup()
{
	if(channel<maxchannel)
		channel++;
	else
		channel=1;
}
void Tv::chandown()
{
	if(channel>1)
		channel--;
	else
		channel=maxchannel;
}

void Tv::setting()const
{
	cout<<"Tv is "<<(state==Off?"off":"on")<<endl;
	if(state==On)
	{
		cout<<"Volume setting="<<volume<<endl;
		cout<<"Channel setting="<<channel<<endl;
		cout<<"Mode="<<(mode==Antenna?"antenna":"cable")<<endl;
		cout<<"Input="<<(input==TV?"Tv":"DVD")<<endl;
	}
}
void Tv::setR(Remote &r)
{
		if(state==On)
			r.change();
		else
			cout<<"Tv is not on!"<<endl;
}

main151.cpp

#include "tv.h"
#include <iostream>
using namespace std;

void main151()
{
	/*
	Tv t;
	cout<<"Initial setting for t"<<endl;
	t.setting();
	t.onoff();
	t.chanup();
	cout<<"\nAdjusted settings for t"<<endl;
	t.setting();
	t.chanup();
	cout<<"Adjusted setting for t"<<endl;
	t.setting();
	*/
	Remote grey;
	/*
	grey.set_chan(t,10);
	grey.volup(t);
	grey.volup(t);
	cout<<"t \"settings after using remote:"<<endl;
	t.setting();
	*/
	Tv t11(Tv::On);
	t11.setting();
	grey.set_chan(t11,28);
	cout<<"t11 settings "<<endl;
	t11.setting();

	grey.show();
	t11.setR(grey);
	grey.show();









}

 

 


发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注