From b4e603d6018a0b43ad3ce9d3a1900ce784a2d07b Mon Sep 17 00:00:00 2001 From: angeld55 Date: Wed, 16 Jun 2021 16:56:02 +0300 Subject: utills --- Utills/si_14.06/task1/Optional/Optional.hpp | 109 ++++++++++++++++++++++++++++ Utills/si_14.06/task1/Source.cpp | 17 +++++ 2 files changed, 126 insertions(+) create mode 100644 Utills/si_14.06/task1/Optional/Optional.hpp create mode 100644 Utills/si_14.06/task1/Source.cpp (limited to 'Utills/si_14.06/task1') diff --git a/Utills/si_14.06/task1/Optional/Optional.hpp b/Utills/si_14.06/task1/Optional/Optional.hpp new file mode 100644 index 0000000..cf1ec0d --- /dev/null +++ b/Utills/si_14.06/task1/Optional/Optional.hpp @@ -0,0 +1,109 @@ +#include + +template +class Optional +{ + T* objPtr; + + void copyFrom(const Optional& other); + void free(); + +public: + Optional(); + Optional(const T& obj); + + Optional(const Optional& other); + Optional& operator=(const Optional& other); + + ~Optional(); + + void setValue(const T& obj); + T getValue() const; + + bool containsValue() const; + + bool operator==(const Optional& other) const; + bool operator!=(const Optional& other) const; +}; + +template +Optional::Optional() : objPtr(nullptr) +{}; + +template +Optional::Optional(const T& obj) +{ + objPtr = new T(obj); +} + +template +void Optional::setValue(const T& obj) +{ + delete objPtr; + objPtr = new T(obj); +} + +template +T Optional::getValue() const +{ + if (!obj) + throw std::exception("No value assigned!"); + return *objPtr; +} + +template +bool Optional::containsValue() const +{ + return objPtr != nullptr; +} + +template +void Optional::copyFrom(const Optional& other) +{ + if (!other.obj) + objPtr = nullptr; + else + objPtr = new T(*other.obj); +} + +template +void Optional::free() +{ + delete objPtr; +} + +template +Optional::Optional(const Optional& other) +{ + copyFrom(other); +} + +template +Optional& Optional::operator=(const Optional& other) +{ + if (this != &other) + { + free(); + copyFrom(other); + } + + return *this; +} + +template +Optional::~Optional() +{ + free(); +} + +template +bool Optional::operator==(const Optional& other) const +{ + return (!objPtr && !other.objPtr) || (objPtr && other.objPtr && *objPtr == *other.objPtr); +} + +template +bool Optional::operator!=(const Optional& other) const +{ + return !operator==(other); +} diff --git a/Utills/si_14.06/task1/Source.cpp b/Utills/si_14.06/task1/Source.cpp new file mode 100644 index 0000000..d8397a0 --- /dev/null +++ b/Utills/si_14.06/task1/Source.cpp @@ -0,0 +1,17 @@ +#include +#include "Optional/Optional.hpp" + + + +int main() +{ + Optional o; + + std::cout << o.containsValue() << std::endl; + + o.setValue(12); + + Optional o2(12); + + std::cout << (o == o2) << std::endl; +} \ No newline at end of file -- cgit v1.3.1-23-gd82d