生活中简单的电视和遥控器,遥控器既不能继承电视,也不属于组合关系,此时使用友元类,让遥控器可以控制电视。
对例子进行简化,只有电视的开关状态和频道的增加/减少,设置最大频道数125
// tv.h -- Tv and Remote classes
#ifndef TV_H_
#define TV_H_
#include <iostream>
using namespace std;
class Tv
{
public:
friend class Remote; // Remote can access Tv private parts
enum {Off, On};
Tv(int s = Off, int mc = 125) : state(s), maxchannel(mc),
channel(2) {}
void onoff() {state = (state == On) ? Off : On;}
bool ison() const {return state == On;}
void chanup();
void chandown();
private:
int state;
int maxchannel;
int channel;
};
class Remote
{
public:
Remote() {}
void onoff(Tv & t) {t.onoff(); cout << "Tv is on/off\n";}
void chanup(Tv & t) {t.chanup();}
void chandown(Tv & t) {t.chandown();}
};
#endif
// tv.cpp -- methods for the Tv class (Remote methods are inline
#include <iostream>
#include "tv.h"
using namespace std;
void Tv::chanup()
{
if (channel < maxchannel)
channel++;
else
channel = 1;
cout << "Now channel is " << channel << endl;
}
void Tv::chandown()
{
if (channel > 1)
channel--;
else
channel = maxchannel;
cout << "Now channel is " << channel << endl;
}
// use_tv.cpp -- using the Tv and Remote classes
#include <iostream>
#include "tv.h"
using namespace std;
int main()
{
Tv s42;
s42.onoff();
Remote grey;
grey.onoff(s42);
grey.chanup(s42);
grey.chanup(s42);
grey.chandown(s42);
}
输出:
wang@wang:~/c++$ ./a.out
Tv is on/off
Now channel is 3
Now channel is 4
Now channel is 3