作用:友元类的所有方法都可以访问原始类的私有成员和保护成员。
使用:A类可以修改B类的状态。
#include <iostream>
using namespace std;
#ifndef TV_H_
#define TV_H_
class Tv
{
public:
friend class 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;}
void settings() const;
private:
int state;
int volume;
int maxchannel;
int channel;
int mode;
int input;
};
class Remote
{
public:
Remote(int m = Tv::TV) :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 ();}
private:
int mode;
};
bool Tv::volup ()
{
if(volume <MAXVAL)
{
volume++;
return true;
}
else {
return false;
}
}
bool Tv::voldown ()
{
if(volume >MINVAL)
{
volume--;
return true;
}
else
return false;
}
void Tv::chanup ()
{
if(channel<maxchannel)
channel++;
else {
channel = 1;
}
}
void Tv::chandown ()
{
if(channel >1)
channel--;
else
channel = maxchannel;
}
void Tv::settings () const
{
cout<<"TV is "<<(state == ON?"ON":"OFF")<<endl;
if(state == ON)
{
cout<<"Volume setting ="<<volume<<endl;
cout<<"Channel setting = "<<channel<<endl;
cout<<"Mode ="<<(mode == ANTENNA?"antenna":"cable")<<endl;
cout<<"Input = "<<(input == TV?"TV":"DVD")<<endl;
}
}
#endif
int main()
{
Tv s42;
cout<<"Initial settings for 42\" Tv:\n";
s42.settings ();
s42.onoff ();
s42.chanup ();
cout<<"\nAdjusted settings for 42\" Tv\n";
s42.settings ();
Remote grey;
grey.set_chan (s42,10);
grey.volup (s42);
grey.volup (s42);
cout << "\n42\" settings after using remote\n";
s42.settings ();
}