0

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.

2
  • 1
    I think your approach should have worked. Can you post the error you got? Commented Dec 14, 2013 at 20:00
  • I've got it working now, and my code looks really similar to the one above (except for that the return type of the overload-function is void instead). I think that the reason for the errors had to do with the fact that I, accidently, declared a supposed object of type "output" by just writing "output <name>;" above the actual class (which honestly, didn't look wrong to me at that moment). After changing a couple of other things, and moving that declaration to the proper position (after the class end block-thingy), it seems to be working. Commented Dec 15, 2013 at 0:20

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Note that the same should have worked as a member function implementation (non-const), which the OP had problems with.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.