【C++OJ_静态与友元】电视机与遥控器(友元类)
题目描述
有如下的电视类和遥控器类,遥控器在电视开机的情况下可以控制电视。
要求如下:
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 <cstring>
using namespace std;
class TV //电影类
{
int state; //电视开关状态,on或者off
int volume; //音量,取值范围从0到20
int maxchannel; //支持最大频道
int channel; //当前频道
int mode; //电视信号接收模式,Cable或者Antenna
int input; //输入方式 VCR或者TV
public:
TV(int s, int v, int c, int m, int i) : state(s), volume(v), maxchannel(100), channel(c), mode(m), input(i) {} //构造函数
void onoff() //切换电视开关状态
{
if (ison() == true)
state = 0;
else
state = 1;
}
bool ison() const // 判断电视开关状态,on返回true
{
if (state == 1)
return true;
else
return false;
}
void volup() //增加音量。执行一次+1
{
if (ison() == true)
{
if (volume == 20)
;
else
volume++;
}
}
void voldown() //降低音量。执行一次-1
{
if (ison() == true)
{
if (volume == 0)
;
else
volume--;
}
}
void chanup() //增加频道数,执行一次+1
{
if (ison() == true)
{
if (channel == 100)
;
else
channel++;
}
}
void chandown() //减少频道数,执行一次-1
{
if (ison() == true)
{
if (channel == 1)
;
else
channel--;
}
}
void set_mode() // 切换电视信号接收模式,初始为Cable
{
if (ison() == true)
{
if (mode == 0)
mode = 1;
else if (mode == 1)
mode = 0;
}
}
void set_input() // 切换电视输入方式,初始为VCR
{
if (ison() == true)
{
if (input == 0)
input = 1;
else if (input == 1)
input = 0;
}
}
void settings() const //按类中成员顺序,输出电视设置信息
{
if (state == 1)
cout << "on ";
else
cout << "off ";
cout << volume << " " << channel << " ";
if (mode == 1)
cout << "Antenna ";
else
cout << "Cable ";
if (input == 1)
cout << "TV";
else
cout << "VCR";
}
friend class Remote; //将Remote设为Tv的友元类,以支持在Remote类中对Tv方法的调用。
};
class Remote
{
int mode; //控制TV or VCR
public:
Remote() {}
Remote(int m) : mode(m) {}
void volup(TV &t) { return t.volup(); }
void 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, s_n, m_n, i_n;
char s[4], m[8], i[4];
cin >> s >> v >> c >> m >> i;
if (strcmp(s, "off") == 0)
s_n = 0;
else
s_n = 1;
if (strcmp(m, "Antenna") == 0)
m_n = 1;
else
m_n = 0;
if (strcmp(i, "TV") == 0)
i_n = 1;
else
i_n = 0;
TV t(s_n, v, c, m_n, i_n);
int tt = 5;
while (tt--)
{
int cc;
Remote r;
char re[10];
cin >> re;
if (strcmp(re, "onoff") == 0)
r.onoff(t);
if (strcmp(re, "volup") == 0)
r.volup(t);
if (strcmp(re, "voldown") == 0)
r.voldown(t);
if (strcmp(re, "chanup") == 0)
r.chanup(t);
if (strcmp(re, "set_chan") == 0)
{
cin >> cc;
r.set_chan(t, cc);
}
if (strcmp(re, "set_mode") == 0)
r.set_mode(t);
if (strcmp(re, "set_input") == 0)
r.set_input(t);
}
t.settings();
cout << endl;
return 0;
}