post lecture 2-2
This commit is contained in:
@@ -21,7 +21,7 @@ int main() {
|
|||||||
for(int i = 0; i < length; i++){
|
for(int i = 0; i < length; i++){
|
||||||
cout << "before seg fault" << endl;
|
cout << "before seg fault" << endl;
|
||||||
// Will use access operator instead
|
// Will use access operator instead
|
||||||
cout << row1.row_data[i] << " ";
|
//cout << row1.row_data[i] << " ";
|
||||||
}
|
}
|
||||||
cout << endl;
|
cout << endl;
|
||||||
|
|
||||||
|
|||||||
@@ -25,3 +25,42 @@ Dog::Dog(const Dog& from){
|
|||||||
this->name[i] = from.name[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;
|
||||||
|
}
|
||||||
@@ -2,9 +2,15 @@ using namespace std;
|
|||||||
|
|
||||||
class Dog {
|
class Dog {
|
||||||
public:
|
public:
|
||||||
Dog(int age, int namelength, char * name);
|
Dog(int age, int namelength, char * name);
|
||||||
~Dog();
|
Dog(const Dog& from);
|
||||||
int age;
|
~Dog();
|
||||||
int namelength;
|
Dog& operator=(const Dog& rhs);
|
||||||
char * name;
|
char operator[](int index) const;
|
||||||
|
char& operator[](int index);
|
||||||
|
friend ostream& operator<<(ostream& os, const Dog& d);
|
||||||
|
private:
|
||||||
|
int age;
|
||||||
|
int namelength;
|
||||||
|
char * name;
|
||||||
};
|
};
|
||||||
Reference in New Issue
Block a user