Could someone help me with operator overloading and my String class. I'm stuck with the '+' operator, which should "return a new object of type CString that contains the contents of 'this' Cstring with the contents of the parameter Cstring concatinated." It supposed to work in 3 different ways: 'CString + Cstring', 'Cstring + char *', and 'char * + Cstring'. I've got no problems with the first two, just the third one that's giving me problems. I think I need a friend function that receives a char * and a CString, then returns a CString, but I'm not sure how to implement that.
Here's some code:
Code:
class CString
{
friend class CStringIterator;
friend CString &operator+ (const char * lvalue, const CString & rvalue);
friend ostream &operator<<(ostream &stream, const CString &rvalue); //works
friend istream &operator>>(istream &stream, CString &rvalue); //works
friend bool operator== (const CString & lvalue, const CString & rvalue);
public:
CString(); //works
CString(CString &string); //works
CString(char*); //works
~CString(); //works
//void Set(char* NewString);
void Set(CString NewString);
bool IsEmpty() const; //works
int Length() const;//works
//void Append(char* NewString); //works but don't need
void Append(CString &NewString); //works
//bool Compare(char* NewString);
bool Compare(CString NewString) const;//works
void Empty(); //works
void Display() const; //works
void Contain_My_Name() const; //works
/*//////// Begin Overloaded Operators ////////////////*/
const CString &CString::operator=(const CString & rValue);
CString &operator+ (const CString & rvalue);
void CString::operator+=(const CString &rvalue);
bool CString::operator== (const CString & rvalue) const;
bool CString::operator< (const CString & rvalue) const;
bool CString::operator> (const CString & rvalue) const;
bool CString::operator<= (const CString & rvalue) const;
bool CString::operator>= (const CString & rvalue) const;
bool CString::operator!= (const CString & rvalue) const;
private:
char* pString;
void SetString(const char * string, int length);
};
Member function for overload operator+ that works great:
Code:
CString &CString::operator+ (const CString & rvalue)
{
int l1 = Length();
int l2 = rvalue.Length();
int length = l1 + l2;
char *tempPtr = new char[length + 1];
strcpy(tempPtr, pString);
strcpy(tempPtr + l1, rvalue.pString);
delete [] pString;
pString = tempPtr;
return * this;
}
Friend function for operator+ that doesn't work:
Code:
CString &operator+ (const char * lvalue, const CString & rvalue)
{
int l1, l2;
l1 = strlen(rvalue.pString);
l2 = rvalue.Length();
char *tempPtr = new char[l1 + l2 + 1];
strcpy(tempPtr, lvalue);
strcpy(tempPtr + l1, rvalue.pString);
CString new_string;
new_string = tempPtr;
delete [] tempPtr;
return * new_string;
}
Thanks for any help in advance!