cout << 1 << 2 << 3 << 4;
This way this works is as a series of calls with two arguments e.g.
(((cout << 1) << 2) << 3) << 4;
Which is roughly equivalent to this:
cout << 1;
cout << 2;
cout << 3;
cout << 4;
So you don't write an operator<<
taking multiple parameters, it always takes two operands, the left operand and the right operand. The left operand in the example above is cout
i.e. the ostream
and the right operand is the int
being written to it. The operator returns the left operand, allowing it to be used again in the next operation, and so on for as many <<
operations as you chain together.
So cout << 1
returns cout
again, so that (cout << 1) << 2
invokes the operator to write 1 to the stream and return the stream, then invokes the operator again on the return value to write 2 to the stream and then returns the stream again.
This is just nonsense:
friend int operator<<(const int &x, const int &y)
{
data += x;
data += y;
}
Where is data
supposed to come from? A friend function is not a member of the class, so there is no this
pointer, so no this->data
, also you claim to return int
but don't return anything, and this class is completely unrelated to Test
. What you've written is an operator<<
for two ints i.e. for doing 1 << 2
but that operator already exists, it's the bitshift operator, and you can't overload it for built-in types like int
.
You want:
class Test
{
private:
int data;
public:
Test() { data = 0; }
void print() { cout << data; }
Test& operator<<(int y)
{
data += x;
return *this;
}
};
Or as a friend:
class Test
{
private:
int data;
public:
Test() { data = 0; }
void print() { cout << data; }
friend Test& operator<<(Test& t, int y)
{
t.data += x;
return t;
}
};