ex02: fix and add test

This commit is contained in:
Camille Chauvet 2023-10-04 14:42:46 +00:00
parent 90b510cf0c
commit 810105e554
3 changed files with 49 additions and 8 deletions

View File

@ -4,7 +4,7 @@ SRCDIR := src
OBJDIR := obj OBJDIR := obj
NAME := ex02 NAME := ex02
SRCS := $(wildcard $(SRCDIR)/*.tpp) SRCS := $(wildcard $(SRCDIR)/*.cpp)
OBJS := $(patsubst $(SRCDIR)/%.cpp,$(OBJDIR)/%.o,$(SRCS)) OBJS := $(patsubst $(SRCDIR)/%.cpp,$(OBJDIR)/%.o,$(SRCS))
all: $(NAME) all: $(NAME)

View File

@ -11,14 +11,17 @@ class Array
unsigned int _size; unsigned int _size;
public: public:
Array(): Array():
_arr(new T[0]), _arr(new T[0]),
_size(0) _size(0)
{}; {};
Array(unsigned int n): Array(unsigned int n):
_arr(new T[n]), _arr(new T[n]),
_size(n) _size(n)
{}; {};
Array(const Array& src) Array(const Array& src)
{ {
new T[0]; new T[0];
@ -33,22 +36,23 @@ class Array
Array& operator=(const Array& src)\ Array& operator=(const Array& src)\
{ {
if (this == &src) if (this == &src)
return ; return *this;
delete[] this->_arr; delete[] this->_arr;
this->_size = src._size; this->_size = src._size;
new T[src._size]; new T[src._size];
for (size_t i = 0; i < src._size; i++) for (size_t i = 0; i < src._size; i++)
this->_arr[i] = src._arr[i]; this->_arr[i] = src._arr[i];
}; };
Array& operator[](unsigned int index)
T& operator[](unsigned int index) const
{ {
if (index >= _size) if (index >= _size)
throw std::exception(); throw std::exception();
return _arr[index]; return this->_arr[index];
}; };
unsigned int size() const unsigned int size() const
{ {
return _size; return this->_size;
}; };
}; };

37
ex02/src/main.cpp Normal file
View File

@ -0,0 +1,37 @@
#include "Array.hpp"
#include <exception>
#include <iostream>
int main()
{
std::cout << "Create with 0 size" << std::endl;
{
Array<int> t(0);
}
std::cout << std::endl;
std::cout << "Access to invalid index ";
{
Array<int> t(0);
try
{
t[0];
std::cout << "failed !" << std::endl;
}
catch (std::exception& e)
{
std::cout << "success !" << std::endl;
}
}
std::cout << "Fill and get";
{
unsigned int size = 10;
Array<int> t(size);
for (unsigned int i = 0; i != size; i++)
t[i] = i;
for (unsigned int i = 0; i != size; i++)
std::cout << i << std::endl;
}
std::cout << std::endl;
}