代码摘自c++primer plus
【注】:友元类的声明的声明可以调用另一个类的私有成员
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; //Remote类可以访问Tv类的私有部分
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;//控制TV或者DVD模式
public:
Remote(int m = Tv::TV) : mode(m) {}
bool volup(Tv & t) {return t.volup();}
bool voldown(Tv & t) {return t.voldown();}
bool onoff(Tv & t) { t.onoff();}
bool chanup(Tv & t) { t.chanup();}
bool 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();}
};
#endif
tv.cpp实现类的函数
#include <iostream>
#include "TV.h"
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 = maxchannel;
}
void Tv::settings() const
{
using std::cout;
using std::endl;
cout << "Tv is "<<(state == OFF?"OFF":"ON") << 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;
}
}
user_tv.cpp对类的使用
#include<iostream>
#include"TV.h"
int main()
{
using std::cout;
Tv s42;
cout << "Inint settings for 42 号电视\" TV:\n";
s42.settings();
s42.onoff();
s42.chanup();
cout << "\nAdjusted settings for 42号电视机\" TV :\n";
s42.chanup();
cout << " \n Adjusted 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();
Tv s58(Tv::ON);
s58.set_mode();
grey.set_chan(s58,28);
cout << "\n58\" settings:\n";
s58.settings();
return 0;
}
Makefile
makefile基础编写讲解
CC = g++
objects = tv.o use_tv.o
tv:$(objects)
$(CC) -o tv $(objects)
tv.o: TV.h
use_tv.o:TV.h
clean:
rm -rf tv $(objects)
运行结果: