-2

I was just asking if you can create your own cout<< like object in C++. most people confuse my question with operator overloading <<. But no, i dont want to implement my own << operator so that when users print my object i can control what they get. But basically i want to implement like this:

something << some_given << some_end;

Not sure if that is possible , but the iostream standard library created the cout , so my mind says "Why not?". So i asked stackoverflow. Help would be appreciated! :)

amanuel2
  • 4,508
  • 4
  • 36
  • 67

1 Answers1

3

I'm not sure if I interpretted your question correctly but I think you want a class with an overloaded operator<< so that's what i have here

class MyClass {
  public:
    MyClass() = default;
    MyClass& operator<<(int input) {
      //do something with input
      return *this;
    }
}

You would use it like this;

MyClass myObject;
myObject << 42;
//the function would have been called
Indiana Kernick
  • 5,041
  • 2
  • 20
  • 50
  • Thanks thats what i wanted! – amanuel2 Jul 25 '16 at 03:28
  • 2
    best way is to make `operator <<` return reference, like this: `MyClass &operator << (...);` so you would be able to write several << in one line: `myObject << 42 << 37 << 14;`. – Andrei R. Jul 25 '16 at 03:31