I am preparing myself for some job interviews. This is a simple array (with the error handling left out for brevity). Any input or suggestions on style and the use of templates would be appreciated.
#include <iostream>
template <class T>
class Array {
public:
explicit Array(const int&);
Array(const int&, const T&);
Array(const Array&);
virtual ~Array();
T getVal(const int&) const;
void setVal(const int&, const T&);
T& operator[] (T);
Array& operator= (const Array&);
template <class U>
friend std::ostream& operator<< (std::ostream&, const Array<U>&);
private:
T* arr;
int size;
};
template <class T>
Array<T>::Array(const int& init_size) {
arr = new T[init_size];
size = init_size;
}
template <class T>
Array<T>::Array(const int& init_size, const T& init_value) {
arr = new T[init_size];
size = init_size;
for (int i = 0; i < size; ++i) {
arr[i] = init_value;
}
}
template <class T>
Array<T>::Array(const Array& original) {
size = original.size;
arr = new T[size];
for (int i = 0; i < size; ++i) {
arr[i] = original.arr[i];
}
}
template <class T>
Array<T>::~Array() {
delete [] arr;
}
template <class T>
T Array<T>::getVal(const int& index) const {
return arr[index];
}
template <class T>
void Array<T>::setVal(const int& index, const T& value) {
arr[index] = value;
}
template <class T>
T& Array<T>::operator[] (T index) {
return arr[index];
}
template <class T>
Array<T>& Array<T>::operator= (const Array& copy) {
if (arr == copy.arr)
return *this;
size = copy.size;
delete [] arr;
arr = new T[size];
for (int i = 0; i < size; ++i) {
arr[i] = copy.arr[i];
}
return *this;
}
template <class T>
std::ostream& operator<< (std::ostream& out, const Array<T>& self) {
out << "[ ";
for (int i = 0; i < self.size-1; ++i) {
out << self.arr[i] << ", ";
}
out << self.arr[self.size-1] << " ]";
return out;
}