From cdd5b6c28b12a4763c9b1eef9ba45ca85a6ddaa2 Mon Sep 17 00:00:00 2001 From: Syndamia Date: Wed, 20 Mar 2024 13:20:09 +0200 Subject: [w4] Solved exercises 1-5 --- week04/Exercise4.cpp | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 week04/Exercise4.cpp (limited to 'week04/Exercise4.cpp') diff --git a/week04/Exercise4.cpp b/week04/Exercise4.cpp new file mode 100644 index 0000000..3716287 --- /dev/null +++ b/week04/Exercise4.cpp @@ -0,0 +1,47 @@ +#include +#include + +struct DynamicString { +private: + char* str; + int size; + + void copyFrom(const DynamicString& other) { + this->str = new char[other.size + 1]; + strncpy(this->str, other.str, other.size + 1); + this->size = other.size; + } + + void free() { + delete[] str; + } + +public: + DynamicString(const char* str) { + size = strlen(str); + this->str = new char[size + 1]; + strncpy(this->str, str, size + 1); + } + ~DynamicString() { + free(); + } + + DynamicString& operator=(const DynamicString& other) { + if (this != &other) { + free(); + copyFrom(other); + } + return *this; + } + + const char* GetStr() { + return str; + } +}; + +int main() { + DynamicString s1("Hello"); + DynamicString s2("World"); + s1 = s2; + std::cout << s1.GetStr() << std::endl; +} -- cgit v1.2.3