Question

I am writing my own integer class that can handle integers of any size. So far, I have overloaded the following operators successfully: =, +, -, *, /, %, >, <, >=, <=, ==, !=, +=, -=, *=, /=, and %=.

Now, I'm trying to overload the << operator to mimic the behavior of int's in the following lines of code:

int a = 5;
std::cout << a;

I have been looking at how to do this for a while, and so far all I've found is this:

std::ostream& operator<<(std::ostream& os, const T& obj)
{
  // Write obj to stream
  return os;
}

But this seems to be for if I wanted to stream something into my object (that is, having the << on the right side of my object). But I want to change the behavior of << when it is on the LEFT side of my object.

How can I set up the operator<< function to allow me to stream data into cout (or any other ostream)?

Was it helpful?

Solution

How can I set up the operator<< function to allow me to stream data into cout (or any other ostream)?

The way you did here:

std::ostream& operator<<(std::ostream& os, const T& obj)
{
  // write obj to stream
  return os;
}

As others usefully pointed out in the comments, you will need to place it outside of your integer classes to be a "free function". It could still be the member of your integer classes, but yeah, that is it.

But this seems to be for if I wanted to stream something into my object. (i.e. having the << on the right side of my object). But I want to change the behavior of << when it is on the LEFT side of my object.

I am not sure where you got that from but the first argument is the left side argument which is the output stream in your case, and the second is the instance of your integer class that gets written to that output stream.

OTHER TIPS

In C++ streams,

std::cout << a;

is just syntactic sugar for

operator<<(std::cout, a);

which matches the signature

std::ostream& operator<<(std::ostream& os, const int &a);

So likewise,

std::cout << myBigInt;

would be syntactic sugar for

operator<<(cstd::cout, myBigInt);

Therefore the snippet you posted enables the syntax

os << obj; // os is an ostream; obj is a T

In other words, the << is on the left side of obj and/or myBigInt since the binary operator goes in between the two operands that you see in the function argument list.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top