Convert add operator to a friend operator

By replacing the addition operator with a friend operator, order of
operations doesn’t matter, provided that at least one argument is a
ManagedString.

```C++
ManagedString a = "A";           // OK
ManagedString b = a + ", " + 2;  // OK
ManagedString c = "a" + a + 2;   // OK
ManagedString d = 1 + "," + 2;   // FAILS
```
This commit is contained in:
Brendan Moran 2016-05-12 13:23:27 +01:00 committed by James Devine
parent d887bbf670
commit 8468823e21
2 changed files with 15 additions and 12 deletions

View File

@ -300,9 +300,10 @@ class ManagedString
ManagedString substring(int16_t start, int16_t length);
/**
* Concatenates this string with the one provided.
* Concatenates two strings.
*
* @param s The ManagedString to concatenate.
* @param lhs The first ManagedString to concatenate.
* @param rhs The second ManagedString to concatenate.
*
* @return a new ManagedString representing the joined strings.
*
@ -314,7 +315,7 @@ class ManagedString
* display.scroll(s + p) // scrolls "abcdefgh"
* @endcode
*/
ManagedString operator+ (const ManagedString& s);
friend ManagedString operator+ (const ManagedString& lhs, const ManagedString& rhs);
/**
* Provides a character value at a given position in the string, indexed from zero.

View File

@ -437,9 +437,10 @@ ManagedString ManagedString::substring(int16_t start, int16_t length)
}
/**
* Concatenates this string with the one provided.
* Concatenates two strings.
*
* @param s The ManagedString to concatenate.
* @param lhs The first ManagedString to concatenate.
* @param rhs The second ManagedString to concatenate.
*
* @return a new ManagedString representing the joined strings.
*
@ -451,16 +452,17 @@ ManagedString ManagedString::substring(int16_t start, int16_t length)
* display.scroll(s + p) // scrolls "abcdefgh"
* @endcode
*/
ManagedString ManagedString::operator+ (const ManagedString& s)
ManagedString operator+ (const ManagedString& lhs, const ManagedString& rhs)
{
// If the other string is empty, nothing to do!
if(s.length() == 0)
return *this;
if (length() == 0)
return s;
// If the either string is empty, nothing to do!
if (rhs.length() == 0)
return lhs;
return ManagedString(*this, s);
if (lhs.length() == 0)
return rhs;
return ManagedString(lhs, rhs);
}