From 810105e55458e7f4552ff47ea5acd4c50c25778b Mon Sep 17 00:00:00 2001 From: Camille Chauvet Date: Wed, 4 Oct 2023 14:42:46 +0000 Subject: [PATCH] ex02: fix and add test --- ex02/Makefile | 4 ++-- ex02/src/Array.hpp | 16 ++++++++++------ ex02/src/main.cpp | 37 +++++++++++++++++++++++++++++++++++++ 3 files changed, 49 insertions(+), 8 deletions(-) create mode 100644 ex02/src/main.cpp diff --git a/ex02/Makefile b/ex02/Makefile index 45bb44c..9b9a653 100644 --- a/ex02/Makefile +++ b/ex02/Makefile @@ -4,7 +4,7 @@ SRCDIR := src OBJDIR := obj NAME := ex02 -SRCS := $(wildcard $(SRCDIR)/*.tpp) +SRCS := $(wildcard $(SRCDIR)/*.cpp) OBJS := $(patsubst $(SRCDIR)/%.cpp,$(OBJDIR)/%.o,$(SRCS)) all: $(NAME) @@ -23,4 +23,4 @@ fclean: clean rm -fr $(NAME) re: fclean - @make --no-print-directory all \ No newline at end of file + @make --no-print-directory all diff --git a/ex02/src/Array.hpp b/ex02/src/Array.hpp index d653dac..853074c 100644 --- a/ex02/src/Array.hpp +++ b/ex02/src/Array.hpp @@ -11,15 +11,18 @@ class Array unsigned int _size; public: + Array(): _arr(new T[0]), _size(0) {}; - Array(unsigned int n): + + Array(unsigned int n): _arr(new T[n]), _size(n) {}; - Array(const Array& src) + + Array(const Array& src) { new T[0]; *this = src; @@ -33,22 +36,23 @@ class Array Array& operator=(const Array& src)\ { if (this == &src) - return ; + return *this; delete[] this->_arr; this->_size = src._size; new T[src._size]; for (size_t i = 0; i < src._size; i++) this->_arr[i] = src._arr[i]; }; - Array& operator[](unsigned int index) + + T& operator[](unsigned int index) const { if (index >= _size) throw std::exception(); - return _arr[index]; + return this->_arr[index]; }; unsigned int size() const { - return _size; + return this->_size; }; }; diff --git a/ex02/src/main.cpp b/ex02/src/main.cpp new file mode 100644 index 0000000..c9afcdb --- /dev/null +++ b/ex02/src/main.cpp @@ -0,0 +1,37 @@ +#include "Array.hpp" +#include +#include + +int main() +{ + std::cout << "Create with 0 size" << std::endl; + { + Array t(0); + } + std::cout << std::endl; + + std::cout << "Access to invalid index "; + { + Array 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 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; +}