Files
cpp07/ex02/Array.hpp

57 lines
965 B
C++

#include <cstddef>
#include <exception>
#include <iterator>
#include <string>
template <typename T> class Array {
public:
Array(): _arr(new T[0]), _size(0) {}
Array(const int n): _arr(new T[n]), _size(n) {}
Array(const Array &cpy) {*this = cpy;}
~Array(void) {delete[] _arr;}
Array &operator=(const Array &cpy)
{
if (this != &cpy) {
_size = cpy._size;
_arr = new T[_size];
if (_arr)
{
for (std::size_t i = 0; i < _size; i++)
_arr[i] = cpy._arr[i];
}
}
return (*this);
}
T &operator[](const size_t &pos)
{
if (pos < 0 || pos >= _size)
{
throw outOfBoundException();
}
return _arr[pos];
}
T &operator[](const size_t &pos) const
{
if (pos < 0 || pos >= _size)
{
throw outOfBoundException();
}
return _arr[pos];
}
class outOfBoundException : public std::exception {
virtual const char *what() const throw()
{
return ("value is out of bound");
}
};
private:
T *_arr;
size_t _size;
};