TV.h
#pragma once
#ifndef TV_H_
#define TV_H_
//class Remote; #使用前向声明 让TV类知道Remote是一个类
class Tv {
private:
int state;
int volume;
int maxchannel;
int channel;
int mode;
int input;
public:
friend class Remote;//与Remote是友元
enum{off,on};
enum{MinVal,MaxVal=20};
enum{Antenna,Cable};
enum{TV,DVD};
Tv(int s = off, int mc = 125) :state(s), volume(5),
maxchannel(mc), channel(2), mode(Cable), input(TV) {};
void onoff() { state = (state == on) ? off : on; }//电视是否打开
bool ison()const { return state == on; }
bool volup();//音量调节
bool voldown();
void chanup();//频道切换
void chandown();
void set_mode() { mode = (mode == Antenna) ? Cable : Antenna; }//有线还是无线
void set_input() { input = (input == TV) ? DVD : TV; }//电视还是DVD
bool remote_mode(Remote & r);//遥控器处于常规还是互动模式
void settings(Remote & r)const;//显示所有设置
};
class Remote {
private:
friend class Tv;
int mode;
int remote_model;
public:
enum { Con, Take };
Remote(int m = Tv::TV,int r = Con) :mode(m),remote_model(r) {}
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(); }
void display()const;//显示常规还是互动模式
};
#endif
TV.cpp
#include "TV.h"
#include <iostream>
bool Tv::volup()
{
if (volume < MaxVal)
{
volume++;
return true;
}
return false;
}
bool Tv::voldown()
{
if (volume > MinVal)
{
volume--;
return true;
}
return false;
}
void Tv::chanup()
{
if (channel < maxchannel)
channel++;
else
channel = 1;
}
void Tv::chandown()
{
if (channel > 1)
channel--;
else
channel = maxchannel;
}
bool Tv::remote_mode(Remote & r)
{
if (state == on)
{
r.remote_model = (r.remote_model == Remote::Con) ? Remote::Take : Remote::Con;
return true;
}
return false;
}
void Tv::settings(Remote & r) const
{
using std::cout;
using std::endl;
cout << "TV is " << (state == off ? "Off" : "On") << endl;
if (state == on)
{
cout << "Volume setting = " << volume << endl
<< "Channel setting = " << channel << endl
<< "Mode = "
<< (mode == Antenna ? "antenna" : "cable") << endl
<< "Input = "
<< (input == TV ? "TV" : "DVD") << endl
<< "Remote model = ";
r.display();
cout << endl;
}
}
void Remote::display() const
{
std::cout << (remote_model == Con ? "Con" : "Take");
}
main.cpp
#include <iostream>
#include "TV.h"
int main()
{
using std::cout;
using std::cin;
Tv s42;
Remote grey;
cout << "Initial settings for 42\" TV:\n";
s42.settings(grey);
s42.onoff();
s42.chanup();
cout << "\nAdjusted settings for 42 \" TV:\n";
s42.chanup();
s42.remote_mode(grey);
cout << "\nAdjusted settings for 42 \" TV:\n";
s42.settings(grey);
grey.set_chan(s42, 10);
grey.volup(s42);
grey.volup(s42);
cout << "\n42\" settings after using remote :\n";
s42.settings(grey);
Tv s58(Tv::on);
s58.set_mode();
s58.remote_mode(grey);
grey.set_chan(s58, 28);
cout << "\n58\" settings: \n";
s58.settings(grey);
cin.get();
return 0;
}