Reputation: 887
I want to use an overloaded operation for the operator <<
in a class. I know how to do this between two classes:
class output
{
public:
string x;
output (string a) : x(a) {}
output () {}
output operator<< (const output&);
};
output output::operator<< (const output& a)
{
/* return something that has to do with a.x and x, to make an operation */
}
This works when using x = y << z
, if all are of the same class, and if the operation-overload function returns a suitable value. But, the problem is, that I want one part of the operation to be a string (so basically, x
and y
would have the type output
, and z
the type string
). I was hoping that this would work:
output output::operator<< (const string& a)
...but it doesn't. So I'm starting to suspect that I'm either misunderstanding the use of the whole thing, or that I'm just trying to do something that won't make sense at all... I've tried searching a bit, but couldn't find anything. But if so, what am I misunderstanding exactly? And is there any other way of achieveing what I want?
Help would be greatly appreciated.
Upvotes: 0
Views: 91
Reputation: 5766
You can declare the operator overload as a non-member function. That will let you specify the left and right-hand operand types.
output & operator << (output &lhs, const string &rhs)
{
// do something with lhs and rhs
return lhs;
}
For this kind of operator, I suspect you would also want to return the output
object by reference (although that entirely depends on what you're doing with it).
Upvotes: 1