今天学习了用C++编写一个遥控器
#include <iostream>
using namespace std;
class TV
{
friend class Remote;
enum {On,Off};//电视机状态
enum {minVol,maxVol=100};//音量从0到100
enum {minChannel=1,maxChannel=255};//频道从1到255
private:
int mState;//电视机状态
int nVolume;//电视机音量
int mChannel;//电视频道
public:
TV()//无参初始化
{
this->mState=Off;//默认关机
this->nVolume=minVol;//音量为零
this->mChannel=minChannel;//电视频道为1
}
void onoroff(void)//电视机让他处于关的状态
{
this->mState=(this->mState==On ? Off:On);
}
//音量加大一次
void volumeUp(void)
{
if(this->nVolume>=maxVol)
return;
this->nVolume++;
}
//音量减小一次
void volumeDown(void)
{
if(this->nVolume<=minVol)
return;
this->nVolume--;
}
//增加频道
void channelup(void)
{
if(this->mChannel>=maxChannel)
return;
this->mChannel++;
}
//减少频道
void channelDown(void)
{
if(this->mChannel<=minChannel)
return;
this->mChannel--;
}
//显示电视机状态
void showTVstate(void)
{
cout<<"电视机的状态为:"<<(this->mState==On?"开机":"关机")<<endl;
cout<<"电视机的音量:"<<this->nVolume<<endl;
cout<<"电视机的频道:"<<this->mChannel<<endl;
}
};
//遥控器类
class Remote
{
private:
TV *ptV;
public:
Remote(TV*pTv)
{
this->ptV=pTv;
}
//音量的加减
void volumeUp(void)
{
//调节的电视机的音量
this->ptV->volumeUp();//加 调用TV中的函数
}
void volumeDown(void)
{
this->ptV->volumeDown();//减 调用TV中的函数
}
//频道的加减
void channelUp(void)
{
this->ptV->channelup();//加 调用TV中的函数
}
void channelDown(void)
{
this->ptV->channelDown();//减 调用TV中的函数
}
//电视开关
void onORoff()
{
this->ptV->onoroff();//调用TV中的函数
}
//遥控器设置 频道设置
void setChannel(int num)
{
//判断 频道 是否有效
if(num>=TV::minChannel&&num<=TV::maxChannel)
{
this->ptV->mChannel=num;
}
}
void showTVState(void)//调用TV中的函数 显示电视机状态
{
this->ptV->showTVstate();
}
};
void test03()
{
TV tv;
Remote remote(&tv);
remote.onORoff();
remote.volumeUp();
remote.channelUp();
remote.showTVState();
remote.setChannel(75);
remote.showTVState();
/*
tv.onoroff();//开始
tv.volumeUp();//调音量
tv.volumeUp();
tv.volumeUp();
tv.volumeUp();
tv.channelup();//调频道
tv.channelup();
tv.showTVstate();
*/
}
int main(int argc, char *argv[])
{
test03();
return 0;
}