友元类:
我们创建一个tv类, 一个remote类, 由于遥控器能够对tv进行换台, 因此需要remote类能够访问tv的成员, 所以remote类可以设置成一个友元类, 由于remote类中需要使用到tv的东西, 因此先声明tv, 后声明remote类, 如下所示:
// tv.h
#ifndef TV_H_
#define TV_H_
class Tv
{
private:
int state;
int volume;
int maxchannel;
int channel;
int mode;
int input;
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;
};
class Remote
{
private:
int mode;
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(); }
// 此方法需要直接使用Tv类的私有变量channel, 所以需要友元函数的作用
// 而其他类实际都是使用的Tv的共有方法进行的设置
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();}
};
#endif
第二个文件:
// tv.cpp
#include <iostream>
#include "tv.h"
bool Tv::volup()
{
if(volume < M