電視機與遙控器(友元類)
時間限制: 1 Sec 記憶體限制: 128 MB
送出: 328 解決: 121
[ 送出][ 狀态][ 讨論版]
題目描述
有如下的電視類和遙控器類,遙控器可以控制電視。
要求如下: 1. 實作并完善 Tv 類; 2. 将 Remote 設為 Tv 的友元類,以支援在 Remote 類中對 Tv 方法的調用。 3. 在 main 函數中,通過 Remote 執行個體對 TV 執行個體進行操作。
輸入
第1行,電視初始狀态,依次為state,volume,channel,mode,input的初始值。 第2-n行,利用遙控器對上述狀态的操作指令,用對應的函數名表示,如增加音量為volup,輸入#号則表示操作結束
輸出
輸出執行遙控器操作後的狀态。
樣例輸入
off 10 20 Cable VCR onoff volup chanup set_mode set_input #
樣例輸出
on 11 21 Antenna TV
#include <iostream>
#include <cstring>
using namespace std;
class Tv
{
friend class Remote;
public:
Tv(bool s, int mc) {state=s,volume=0,maxchannel=mc,channel=0,mode=0,input=0;}
void onoff() {state == 1 ? state = 0 : state = 1;}
bool ison() const {return state;}
void set_vol(int v) {volume = v;}
void set_input(int i) {input = i;}
void set_chan(int c) {channel = c;}
bool volup() {
if(state){
if(volume < 20){
volume++;
return 1;
}
return 0;
}
return 0;
}
bool voldown() {
if(state){
if(volume > 0){
volume--;
return 1;
}
return 0;
}
return 0;
}
void chanup() {if(state) if(channel<maxchannel) channel++;}
void chandown() {if(state) if(channel>0) channel--;}
void set_mode() {if(state) mode == 1 ? mode = 0 : mode = 1;}
void set_input() {if(state) input == 1 ? input = 0 : input = 1;}
void settings() const{
if(state == 0) cout << "off ";
else cout << "on ";
cout << volume <<' '<< channel <<' ';
if(mode == 0) cout << "Cable ";
else cout << "Antenna ";
if(input == 0) cout << "VCR\n";
else cout << "TV\n";
}
private:
bool state;
int volume;
int maxchannel;
int channel;
int mode;
int input;
};
class Remote
{
private:
int mode;
public:
Remote(int m) : mode(m){}
bool volup(Tv & t){ return t.volup();}
bool voldown(Tv & t) {return 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();}
};
int main()
{
int v,c,in;
bool st;
char s[4],m[8],i[4];
cin >> s >> v >> c >> m >> i;
if(strcmp(s,"off")==0) st = 0;
else st = 1;
if(strcmp(i,"VCR")==0) in = 0;
else in = 1;
Remote r(in);
Tv tv(st,32);
tv.set_input(in);
tv.set_vol(v);
tv.set_chan(c);
char oper[16];
while(1)
{
cin >> oper;
if(strcmp(oper,"#") == 0)
break;
else if(strcmp(oper,"onoff") == 0)
r.onoff(tv);
else if(strcmp(oper,"volup") == 0)
r.volup(tv);
else if(strcmp(oper,"voldown") == 0)
r.voldown(tv);
else if(strcmp(oper,"chanup") == 0)
r.chanup(tv);
else if(strcmp(oper,"chandown") == 0)
r.chandown(tv);
else if(strcmp(oper,"set_chan") == 0)
{
int no;
cin >> no;
r.set_chan(tv, no);
}
else if(strcmp(oper,"set_mode") == 0)
r.set_mode(tv);
else if(strcmp(oper,"set_input") == 0)
r.set_input(tv);
}
tv.settings();
return 0;
}