Hello,
I've been trying to write a program for a class I'm taking, and have gotten stuck on part of the assignment.
The program is to:
9> Create a template for a safe array. The user will be able to designate the element type and the size of the array. The operations will ensure that no access is allowed outside the bounds of the array. Operations will include [], =, and ==. Instantiate several arrays of different types and sizes and show that the safety features work.
I have the class and template set up, as shown here:
template <class datatype, int size>
class safe_array
{
private:
//Note: array format: TYPE Name[element]
datatype thearray[size];
bool checkbounds(int ub); //Return true if good, false if not.
public:
safe_array();
~safe_array();
datatype operator [] (int index);
datatype operator = (datatype value);
datatype operator == (safe_array& array1);
//These are temporary. They will be used in testing.
void fill();
void print();
};
The rest of the definition is as follows:
template <class datatype, int size>
safe_array<datatype, size>::safe_array()
{
}
template <class datatype, int size>
safe_array<datatype, size>::~safe_array()
{
}
template <class datatype, int size>
bool safe_array<datatype, size>::checkbounds(int ub)
//bool checkbounds(int ub)
{
//ub--upper bound
if (ub <= size)
{
return true;
}
else
{
return false;
}
}
template <class datatype, int size>
datatype safe_array<datatype, size>::operator [](int index)
{
bool goodornot;
goodornot = checkbounds(index);
if (goodornot)
return thearray[index];
else
{
cout << "Run-time error: Index out of bounds.";
cerr << "Index out of bounds!!!";
return -1;
}
}
template <class datatype, int size>
datatype safe_array<datatype, size>::operator = (datatype value)
{
}
template <class datatype, int size>
datatype safe_array<datatype, size>::operator == (safe_array& array1)
{
}
//Temporary
template <class datatype, int size>
void safe_array<datatype, size>::fill()
{
cin >> thearray[1];
cin >> thearray[2];
cin >> thearray[3];
cin >> thearray[4];
}
template <class datatype, int size>
void safe_array<datatype, size>::print()
{
cout << thearray[1] << endl;
cout << thearray[2] << endl;
cout << thearray[3] << endl;
cout << thearray[4] << endl;
}
The template is instantiated with:
safe_array<char, 5> dosomething;
What I want is for this line:
dosomething[5] = 'w';
to do what it would normally do using an array. I'm stuck on writing the assignment operator and lengthy web searches have returned no useful results. What do I need to do?