diff options
Added my work from today's exam
1 files changed, 40 insertions, 0 deletions
| -rw-r--r-- | Year 1/Object-oriented Programming/Exam 2/ex1/String.cpp | 40 |
diff --git a/Year 1/Object-oriented Programming/Exam 2/ex1/String.cpp b/Year 1/Object-oriented Programming/Exam 2/ex1/String.cpp new file mode 100644 index 0000000..693e638 --- /dev/null +++ b/Year 1/Object-oriented Programming/Exam 2/ex1/String.cpp @@ -0,0 +1,40 @@ +#include "String.h" +#include <cstring> + +void String::copyFrom(const String& other) { + length = other.length; + str = new char[length + 1]; + strncpy(str, other.str, length + 1); +} + +void String::free() { + delete[] str; +} + +String::String(const char* str) { + length = strlen(str); + this->str = new char[length + 1]; + strncpy(this->str, str, length + 1); +} + +String::String() : String("") {} + +String::String(const String& other) { + copyFrom(other); +} + +String& String::operator=(const String& other) { + if (this != &other) { + free(); + copyFrom(other); + } + return *this; +} + +String::~String() { + free(); +} + +std::ostream& operator<<(std::ostream& ostr, const String& str) { + return ostr << str.str; +} |
