0

I would like to overwrite the "<<" operator three times. Bottle 2 should give bottle 1 some water.

For example:

Bottle bottle1(200);
Bottle bottle2(200);
bottle1 << 200 << bottle2;

Any ideas?

I tried following in my header file:

friend void operator << (Bottle &a, const int &waterinml);
friend void operator << (const int &waterinml, Bottle &b);

And following in my class source file:

void operator<< (Bottle &a, const int &waterinml)
{
    a.addWater(waterinml);
}

void operator<< (const int &waterinml, Bottle &b)
{
    b.removeWater(waterinml);
}

But that does not work. Overloading once works. For example:

bottle << 200;

would work, but not the example above.

Thank you for your help in advance.

Rkhf
  • 1
  • 1
  • 2
    One of the main points of the `<<` operator is that it *returns* something. Whatever it returns can then be used to chain multiple `<<` operators. – Some programmer dude Dec 02 '20 at 00:48
  • 1
    Both overloads must return a `Bottle` to get this working. – πάντα ῥεῖ Dec 02 '20 at 00:49
  • I also recommend that you make this operator a *member* function instead of a non.member function. That way the operator can return a reference to `*this` for the chaining (the first object, `bottle1`, will then be the left-hand side of the chained `<<` operators). – Some programmer dude Dec 02 '20 at 00:50
  • 1
    `friend Bottle& operator << (Bottle &a, int waterinml) { a.addWater(waterinml); return a; }` `friend Bottle& operator << (Bottle &a, Bottle &b) { a.addWater(b.waterinml); b.waterinml = 0; return a; }` – Remy Lebeau Dec 02 '20 at 01:06

0 Answers0