From 1b8c7458a521dff47e2eeb94489507c542d9cf3a Mon Sep 17 00:00:00 2001 From: barnestr Date: Wed, 16 Mar 2022 14:53:27 -0500 Subject: [PATCH] post lecture 2-2 --- Lab2/main.cpp | 2 +- Lecture/Week2/dog.cpp | 39 +++++++++++++++++++++++++++++++++++++++ Lecture/Week2/dog.h | 16 +++++++++++----- 3 files changed, 51 insertions(+), 6 deletions(-) diff --git a/Lab2/main.cpp b/Lab2/main.cpp index 7f4c05e..97b83a9 100644 --- a/Lab2/main.cpp +++ b/Lab2/main.cpp @@ -21,7 +21,7 @@ int main() { for(int i = 0; i < length; i++){ cout << "before seg fault" << endl; // Will use access operator instead - cout << row1.row_data[i] << " "; + //cout << row1.row_data[i] << " "; } cout << endl; diff --git a/Lecture/Week2/dog.cpp b/Lecture/Week2/dog.cpp index 107089c..ab3302c 100644 --- a/Lecture/Week2/dog.cpp +++ b/Lecture/Week2/dog.cpp @@ -24,4 +24,43 @@ Dog::Dog(const Dog& from){ for(int i = 0; i< this->namelength; i++){ this->name[i] = from.name[i]; } +} + +Dog& Dog::operator=(const Dog& rhs){ + if(&rhs != this){ + // delete existing memory + if(namelength > 0){ + delete[] this->name; + } + this->age = rhs.age; + this->namelength = rhs.namelength; + this->name = new char[namelength]; + for(int i = 0; i < namelength; i++){ + this->name[i] = rhs.name[i]; + } + } + return *this; +} + +char Dog::operator[](int index) const{ + if(index >= namelength){ + // Use with try/catch when called in main do exception e.what() + throw(out_of_range("index is larger than name length")); + } + return name[index]; +} + +char& Dog::operator[](int index){ + if(index >= namelength){ + // Use with try/catch when called in main do exception e.what() + throw(out_of_range("index is larger than name length")); + } + return name[index]; +} + +ostream& operator<<(ostream& os, const Dog& d){ + for(int i = 0; i< d.namelength; i++) { + os << d[i]; + } + return os; } \ No newline at end of file diff --git a/Lecture/Week2/dog.h b/Lecture/Week2/dog.h index ca150fe..9111819 100644 --- a/Lecture/Week2/dog.h +++ b/Lecture/Week2/dog.h @@ -2,9 +2,15 @@ using namespace std; class Dog { public: - Dog(int age, int namelength, char * name); - ~Dog(); - int age; - int namelength; - char * name; + Dog(int age, int namelength, char * name); + Dog(const Dog& from); + ~Dog(); + Dog& operator=(const Dog& rhs); + char operator[](int index) const; + char& operator[](int index); + friend ostream& operator<<(ostream& os, const Dog& d); + private: + int age; + int namelength; + char * name; }; \ No newline at end of file