Sams Teach Yourself C++ in 21 Days

(singke) #1
Answers 871

D


72: cout << “Enter an int: “;
73: cin >> testNumber;
74:
75: // this weird test should be replaced by a series
76: // of tests to complain about bad user input
77:
78: if (testNumber > 3768 || testNumber < 0)
79: throw RangeError(testNumber);
80:
81: *myInt = testNumber;
82: cout << “Ok. myInt: “ << *myInt;
83: delete myInt;
84: }


  1. The following is one possible answer:
    0: // Exercise 20.4
    1: #include
    2: using namespace std;
    3: // Abstract exception data type
    4: class Exception
    5: {
    6: public:
    7: Exception(){}
    8: virtual ~Exception(){}
    9: virtual void PrintError() = 0;
    10: };
    11:
    12: // Derived class to handle memory problems.
    13: // Note no allocation of memory in this class!
    14: class OutOfMemory : public Exception
    15: {
    16: public:
    17: OutOfMemory(){}
    18: ~OutOfMemory(){}
    19: virtual void PrintError();
    20: private:
    21: };
    22:
    23: void OutOfMemory::PrintError()
    24: {
    25: cout << “Out of Memory!!\n”;
    26: }
    27:
    28: // Derived class to handle bad numbers
    29: class RangeError : public Exception
    30: {
    31: public:
    32: RangeError(unsigned long number){badNumber = number;}
    33: ~RangeError(){}
    34: virtual void PrintError();
    35: virtual unsigned long GetNumber() { return badNumber; }


32 0672327112_app_d.qxd 11/19/04 12:30 PM Page 871

Free download pdf