I see two things wrong:
1) remove the const keyword at the end -- the function is not const because it changes the value of stringStorage.
2)You need another class object. What you wrote was for the += operator, not the + operator.
MyString MyString::operator+(const MyString& rightOp)
{
MyString tmp = *this; // requires overloaded = operator
strcpy(tmp.stringStorage, rightOp.stringStorage);
return tmp;
}
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
The addition operator should be overloaded to take two MyStrings, concatenate their text together, and return a new MyString that contains the result.
Don't you want this function to be outside of the class?
class MyString
{
// ...
};
MyString operator+ (const MyString &lhs, const MyString &rhs)
{
return MyString(lhs) + MyString(rhs);
}
Or something like that?
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
Yup -- I tested that too and it compiled ok.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
Don't you want this function to be outside of the class?
class MyString
{
// ...
};
MyString operator+ (const MyString &lhs, const MyString &rhs)
{
return MyString(lhs) + MyString(rhs);
}
Or something like that?
No -- that is illegal syntax for non-class methods. error C2270: '+' : modifiers not allowed on nonmember functions
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
Look at the function I posted above. All you have to do is change the parameter types in the three overloads
MyString MyString::operator+(const MyString& rightOp) const
MyString MyString::operator+(const char* rightOp) const
MyString MyString::operator+(const std::string& rightOp) const
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
char *strcat( char *str1, const char *str2 );
That's the prototype for strcat() from the online reference I usually refer to. I always thought str1 needed to be a null terminated char array and str2 needed to be either a null terminated char array or a string literal. I am also almost certain that the return value of char* will be a null terminated char array. From your previous post I thought that one of the requirements was that the MyString member varialbe called stringStorage could not be null terminated. If that restriction still holds, then you will have to be careful regarding using strcat() and other C style string handling functions to meet the assigment requirements.
Lerner
Nearly a Posting Maven
2,382 posts since Jul 2005
Reputation Points: 739
Solved Threads: 396