56 C++ Primer Plus(第六版)第十五章 编程练习答案
1
tv2.h
# ifndef TV_H_
# define TV_H_
class Remote ;
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 ;
void set_smode ( Remote& r) ;
private :
int state;
int volume;
int maxchannel;
int channel;
int mode;
int input;
} ;
class Remote
{
private :
int mode;
int state_mode;
enum {
Regular, Interact } ;
public :
friend class Tv ;
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 ( ) ; }
void show_smode ( ) const
{
std:: cout << "Now the state mode is:"
<< ( state_mode == Regular ? "Regular" : "Interact" ) << std:: endl;
}
void set_smode ( ) {
state_mode =
( state_mode == Regular ? Interact : Regular) ; }
} ;
inline void Tv :: set_smode ( Remote& r)
{
if ( state == On)
{
r. set_smode ( ) ;
}
else
{
std:: cout << "The Tv is off!\n" ;
}
}
# endif
exercise01_tv2.cpp
# include <iostream>
# include "tv2.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 = 1 ;
}
void Tv :: chandown ( )
{
if ( channel > 1 )
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