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
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
@make --no-print-directory all

View File

@ -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;
};
};

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;
}