题目描述
有如下的电视类和遥控器类,遥控器在电视开机的情况下可以控制电视。
要求如下:
1. 实现并完善Tv类;其中构造函数需修改和完善。另:最大频道为100;
2. 将Remote设为Tv的友元类,以支持在Remote类中对Tv方法的调用。
3. 在main函数中,通过Remote实例对TV实例进行操作。
输入
第一行,电视初始状态,依次为state,volume,channel,mode,input的初始值。
第二行,利用遥控器对上述状态的操作指令,用对应的函数名表示,如增加音量为volup
输出
第一行,执行遥控器操作后的状态。
样例输入
off 10 19 Cable VCR
onoff volup chanup set_mode set_input
样例输出
on 11 20 Antenna TV
#include <iostream>
#include <sstream>
using namespace std;
class Tv{
int state,volume,maxchannel,channel,mode,input;
public:
Tv(int s, int v, int c, int m, int i):maxchannel(100),state(s),volume(v),channel(c),mode(m),input(i) { }
friend class Remote;
void onoff() { state=(state+1)%2; }
bool ison()const{ if(state) return true; return false; }
int getState() { return state; }
void volup() { if(volume<20) ++volume; }
void voldown() { if(volume>0) --volume; }
void chanup() { if(channel<maxchannel) ++channel; }
void chandown() { if(channel>0) --channel; }
void set_mode() { mode=(mode+1)%2; }
void set_input() { input=(input+1)%2; }
void settings() const{
if(state)
cout<<"on ";
else
cout<<"off ";
cout<<volume<<' ';
cout<<channel<<' ';
if(mode)
cout<<"Cable ";
else
cout<<"Antenna ";
if(input)
cout<<"VCR";
else
cout<<"TV";
}
};
class Remote{
int input;
public:
Remote(int i):input(i) { }
void volup(Tv &t) { t.volup(); }
void voldown(Tv &t) { t.voldown(); }
void onoff(Tv &t) { 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 turnStringToInt(int &s,int &v,int &c,int &m,int &i){
string str;
getline(cin,str);
istringstream istr(str);
istr>>str;
if(str=="on")
s=1;
istr>>v;
istr>>c;
istr>>str;
if(str=="Cable")
m=1;
istr>>str;
if(str=="VCR")
i=1;
}
void remoteTv(Remote &r,Tv &t){
string str;
getline(cin,str);
istringstream istr(str);
while(istr>>str){
if(str=="onoff")//如果操作是开关机,则一定会执行
r.onoff(t);
else if(t.getState()){//如果操作不是开关机,只有当前状态为开机才执行操作
if(str=="volup")
r.volup(t);
else if(str=="voldown")
r.voldown(t);
else if(str=="chanup")
r.chanup(t);
else if(str=="chandown")
r.chandown(t);
else if(str=="set_mode")
r.set_mode(t);
else if(str=="set_input")
r.set_input(t);
}
}
}
int main(){
int s,v,c,m,i;
s=v=c=m=i=0;
turnStringToInt(s,v,c,m,i);//把输入中的string转换成int,传引用
Tv tv(s,v,c,m,i);//用转换好的int参数创建一个电视类对象
Remote remote(i);//创建一个遥控器类对象,默认input跟电视一样
remoteTv(remote,tv);//使用遥控器对象改变电视对象的参数值
tv.settings();//根据电视对象中参数的值输出电视的当前状态
return 0;
}