I have to do a homework that requires operator overloading. It's very simple , but i think i forgot alot about operator overloading.
I need to make a premitive string-like class that only has overloaded + and = signs.
Here's the header file :
Code:#ifndef STRTYPE_H #define STRTYPE_H class StrType { public : StrType(char * = "\0"); StrType &operator=(const StrType &); StrType operator+(const StrType &); void print(void); ~StrType(); private : char *ptr; }; #endif
and the .cpp file :
Am i using the proper return types? My C++ book says that = should return a const reference of an object , but that doesn't make sense to me. Also , my operator= function always fail when trying to delete 'ptr' and show an error "debug assertion failed" in VC++. (hilighted in red)Code:#include <iostream> using std::cout; using std::endl; #include <cstring> #include "strtype.h" StrType::StrType(char *str) { ptr = new char[strlen(str) + 1]; strcpy(ptr, str); } StrType &StrType::operator=(const StrType &right) { if( &right != this) { delete [] ptr; // error always occur here ptr = new char[strlen(right.ptr) + 1]; strcpy(ptr, right.ptr); } return *this; } StrType StrType::operator+(const StrType &right) { char *temp = new char[strlen(right.ptr) + strlen(ptr) + 1]; strcpy(temp, ptr); strcat(temp, right.ptr); delete [] ptr; ptr = new char[strlen(temp) + 1]; strcpy(ptr, temp); delete [] temp; return *this; } void StrType::print() { cout << ptr; } StrType::~StrType() { delete [] ptr; }
I used to return a reference to an object in operator+ till i noticed that ' a = b + c + d' would modify objects b , c and d , so i let it return a copy of the object instead.
I just need help in those two operator's logic and return value.



LinkBack URL
About LinkBacks



