Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to overload << operator in c++ to use repeatedly?

Sorry for the not clear title. Recently I started to learn C++ and I don't know how to overload operator << to make it repeatable.

Here's an example code.

class Foo{
private:
int* a;
int idx = 0;

public:
Foo(){a = new int[100];
void operator<< (int a) {arr[idx++] = a;}

What << does is basically class get integer number as an operand and save it into arr.(Ignore overflow case here)

For example, a << 100 will add 100 into array.

What I want to do is make << operator can be repeatedly used inline like a << 100 << 200 How should I fix above code to allow this function?

Thanks in advance :)

like image 733
taegyun kim Avatar asked Feb 02 '26 22:02

taegyun kim


1 Answers

The overloaded Foo::operator<<() takes actually two arguments:

  1. The parameter int given as right-hand side
  2. The implicit this from left-hand side.

To allow chaining of this operator, it should return a reference to the left-hand-side (i.e. *this) to become usable at left-hand-side itself.

Sample code:

#include <iostream>

struct Foo {
  Foo& operator<<(int a)
  {
    std::cout << ' ' << a;
    return *this;
  }
};

int main()
{
  Foo foo;
  foo << 1 << 2 << 3;
}

Output:

 1 2 3

Live demo on coliru

like image 95
Scheff's Cat Avatar answered Feb 05 '26 13:02

Scheff's Cat