Overloading operators: order of operands when using C ++ literals
I'm writing a class and I've gotten to the point where I can do operations that mix class type objects and C ++ literals, but only in one direction.
here's a simplified code that shows the idea:
#include <iostream>
#include <string>
using namespace std;
class CLS
{
string str;
public:
CLS(const char* param)
{ str = param; }
CLS operator+(const CLS& rhs)
{
str = str + rhs.str;
return *this; }
friend ostream& operator<<(ostream& out, const CLS& rhs);
};
ostream& operator<<(ostream& out, const CLS& rhs)
{
out << rhs.str;
return out; }
int main()
{
CLS a("\n Hello ");
CLS b("bye!\n\n");
cout << a + "World!\n\n";
//cout << "\n Good " + b; /* this is not possible because of the operands order */
}
As you can see, I can do something like:
a + "W";
but not,
"W" + a;
As stated in the last line of code.
I understand the reason.
First equivalent:
a.operator+("W");
which is covered by my class. However, the second is similar to
"W".operator(a);
which is not covered and the literal itself is not a class object as I understand it. So the whole expression cannot be.
I understand that I can create custom literals, but that is not what I want to do here. (although I'm not sure if they'll work or not).
I couldn't find any clues to browse that I figured should have been linked on this site, and I couldn't get anything related to my online problem.
My question is:
Is there a way that any order can work?
source to share
This code:
cout << "\n Good " + b; /* this is not possible because of the operands order */
doesn't work because you created a member operator+
(not a constant member). If you rewrite it as a standalone function (maybe a friend) then this problem goes away:
friend
CLS operator+(const CLS& lhs, const CLS& rhs)
{
CLS r;
r.str = lhs.str + rhs.str;
return r;
}
if you create an additional ctor that will accept const std::string &
, it will be even easier:
friend
CLS operator+(const CLS& lhs, const CLS& rhs)
{
return CLS( lhs.str + rhs.str );
}
Note that you must rewrite the existing constructor as follows:
CLS(const char* param) : str( param )
{}
this is a cleaner and more efficient way
source to share