题目要求
编写电视机类,电视机有开机和关机状态,有音量,有频道,提供音量操作的方
法,频道操作的方法。由于电视机只能逐一调整频道,不能指定频道,增加遥控
类,遥控类除了拥有电视机已有的功能,再增加根据输入调台功能。
提示:遥控器可作为电视机类的友元类
封装电视机的类
TV.h
#ifndef TV_H
#define TV_H
#include "remote.h"
class TV
{
private:
friend class Remote;
enum{On,Off};
enum{minVol,maxVol=100};
enum{minChannel=1,maxChannel=255};
private:
int mState;
int mVolume;
int mChannel;
public:
TV();
void onOrOff(void);//开关机
void volUp(void);//音量加
void volDown(void);//音量减
void channelUp(void);//频道加
void channelDowm(void);//频道减
void showTV(void);
};
#endif // TV_H
tv.cpp
#include "tv.h"
#include <iostream>
using namespace std;
TV::TV()
{
this->mState = Off;
this->mVolume=minVol;
this->mChannel=minChannel;
}
void TV::onOrOff(void)//开关机
{
this->mState = (this->mState == On ? Off:On);
}
void TV::volUp(void)//音量加
{
if(this->mVolume >= maxVol)
return;
this->mVolume++;
}
void TV::volDown(void)//音量减
{
if(this->mVolume <=minVol)
return;
this->mVolume++;
}
void TV::channelUp(void)//频道加
{
if(this->mChannel >= maxChannel)
return;
this->mChannel++;
}
void TV::channelDowm(void)//频道减
{
if(this->mChannel <= minChannel)
return;
this->mChannel++;
}
void TV::showTV(void)
{
cout << "电视状态:"<< (this->mState == On ?"开机":"关机")<<endl;
cout << "音量:"<< this->mVolume<<endl;
cout << "频道:"<< this->mChannel<<endl;
}
设置遥控器的类
remote.h
#ifndef REMOTE_H
#define REMOTE_H
#include "tv.h"
#include <iostream>
using namespace std;
class Remote
{
private:
TV *pTv;
public:
Remote(TV *pTv);
void volUp(void);
void volDown(void);
void channelUp(void);
void channelDown(void);
void onOrOff(void);
void showTV(void);
void setChannel(int num);
};
#endif // REMOTE_H
remote.cpp
#include "remote.h"
#include "tv.h"
Remote::Remote(TV *pTv)
{
this->pTv = pTv;
}
void Remote::volUp(void)
{
this->pTv->volUp();
}
void Remote::volDown(void)
{
this->pTv->volDown();
}
void Remote::channelUp(void)
{
this->pTv->channelUp();
}
void Remote::channelDown(void)
{
this->pTv->channelDowm();
}
void Remote::onOrOff(void)
{
this->pTv->onOrOff();
}
void Remote::setChannel(int num)
{
if(num >=TV::minChannel && num <=TV::maxChannel)
{
this->pTv->mChannel = num;
}
else
{
cout << "频道无效"<<endl;
}
}
void Remote::showTV(void)
{
this->pTv->showTV();
}
main.c
#include <iostream>
#include "remote.h"
#include "tv.h"
using namespace std;
void test1()
{
TV tv;
Remote remote(&tv);
remote.onOrOff();
remote.channelUp();
remote.channelUp();
remote.channelUp();
remote.channelUp();
remote.channelUp();
remote.volUp();
remote.volUp();
remote.volUp();
remote.showTV();
remote.setChannel(256);
remote.showTV();
remote.setChannel(66);
remote.showTV();
}
int main(int argc, char *argv[])
{
test1();
return 0;
}
运行结果