Question
C++ Define a class named CheckedArray . The objects of this class are like regular arrays but have range checking. If a is an object
C++
Define a class named CheckedArray. The objects of this class are like regular arrays but have range checking. If a is an object of the class CheckedArray and i is an illegal index, then use of a[i] will cause your program to throw an exception (an object) of the class ArrayOutOfRangeError. Defining the class ArrayOutOfRangeError is part of this project. Note that, among other things, your CheckedArray class must have a suitable overloading of the []operators, as discussed in Appendix 6.
Appendix 6:
You can overload the square brackets, [], for a class so that they can be used with objects of the class. If you want to use [] in an expression on the left-hand side of an assignment operator, then the operator must be defined to return a reference, which is indicated by adding & to the returned type. (This has some similarity to what we discussed for overloading the I/O operators << and >>.) When overloading [], the operator [] must be a member function; the overloaded [] cannot be a friend operator.
For example, the following defines a class called Pair whose objects behave like arrays of characters with the two indexes 1 and 2 (not 0 and 1):
Class Pair
{
public:
Pair();
Pair(char first_value, char second_value);
char& operator[] (int index);
private:
char first;
char second;
};
The definition of the member function [] can be as follows:
char & Pair::operator[] (int index)
{
if (index == 1)
return first;
else if (index == 2)
return second;
else
{
cout << Illegal index value. ;
exit(1);
}
}
Objects are declared and used as follows:
Pair a;
a[1] = A ;
a[2] = B ;
cout << a[i] << a[2] << endl;
Note that in a[1], a is is the calling object and 1 is the argument to the member function [].
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started