题目
1.对Tv和Remote类做如下修改:
a. 让它们互为友元;
b. 在Remote类中添加一个状态变量成员,该成员描述遥控器是处于常规模式还是互动模式;
c. 在Remote中添加一个显示模式的方法;
d. 在Tv类中添加一个对Remote中新成员进行切换的方法,该方法应仅当TV处于打开状态时才能运行。
编写一个小程序来测试这些新特性。
2.修改程序清单15.11,使两种异常类型都是从头文件提供的logic_error类派生出来的类。让每个what()方法都报告函数名和问题的性质。异常对象不用存储错误的参数值,而只需支持what()方法。
3.这个练习与编程练习2相同,但异常类是从一个这样的基类派生而来的:它是从logic_error派生而来的,并存储两个参数值。异常类应该有一个这样的方法:报告这些值以及函数名。程序使用一个catch块来捕获基类异常,其中任何一种从该基类异常派生而来的异常都将导致循环结束。
4.程序清单15.16在每个try后面都使用两个catch块,以确保nbad_index异常导致方法label_val()被调用。请修改该程序,在每个try块后面只使用一个catch块,并使用RTTI来确保合适时调用label_val()。
程序
// tv.h -- Tv and Remote classes
#ifndef TV_H_
#define TV_H_
class Remote;
class Tv
{
public:
friend class Remote; // Remote can access Tv private parts
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; // display all settings
void change_r_mode(Remote & r);
private:
int state; // on or off
int volume; // assumed to be digitized
int maxchannel; // maximum number of channels
int channel; // current channel setting
int mode; // broadcast or cable
int input; // TV or DVD
};
class Remote
{
private:
int mode; // controls TV or DVD
int r_mode;
public:
friend class Tv;
enum {
Regular,Interact};
Remote(int m = Tv::TV,int r=Regular) : mode(m),r_mode(r) {
}
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_r_mode() const{
std::cout<<"The remote is "<<(r_mode==Regular?"Regular":"Interact")<<".\n";}
};
inline void Tv::change_r_mode(Remote & r)
{
if(ison())
r.r_mode=(r.r_mode==Remote::Regular)?Remote::Interact:Remote::Regular;
else
std::cout<<"The tv is off,please turn it in first.\n";
r.show_r_mode();
}
#endif
// tv.cpp -- methods for the Tv class (Remote methods are inline)
#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 = 1;
}
void Tv::chandown()
{
if (channel >