Files
42_INT_09_piscine_cpp/d07/ex02/headers/Array.hpp
2022-03-11 01:54:16 +01:00

51 lines
1.1 KiB
C++

#ifndef ARRAY_HPP
# define ARRAY_HPP
#include <iostream>
template < typename T >
class Array {
public:
Array(unsigned int n = 0u)
: _size(n)
, _arr(new T[n]) {};
~Array() { delete [] _arr; };
Array(Array const & src) : _arr(new T[0]) { *this = src; };
Array &operator=(Array const & rhs) {
if (this == &rhs)
return (*this);
delete[] _arr;
_arr = new T[rhs._size];
_size = rhs._size;
for (unsigned int it = 0; it < rhs._size && it < _size; it++)
_arr[it] = rhs._arr[it];
return (*this);
};
// seen on luke's code :
// https://isocpp.org/wiki/faq/const-correctness#const-overloading
T & operator[](size_t i) {
if (i < 0 || i >= _size)
throw ArrayOutOfRangeException();
return (_arr[i]);
};
const T & operator[](size_t i) const {
if (i < 0 || i >= _size)
throw ArrayOutOfRangeException();
return (_arr[i]);
};
size_t size() const { return (_size); };
private:
class ArrayOutOfRangeException : public std::exception {
const char *what() const throw() {
return ("out of range array index");};
};
size_t _size;
T * _arr;
};
#endif