Why do I need to use "cout" in order for my overloaded "<<" to work properly.

Hi everyone, I'm kinda confused what cout does that suddenly makes my overloaded "<<" function work. I'm going through my code line by line and testing it out. It wouldn't compile when I did this.

1
2
3
4
5
6
7
  ostream& operator<<(ostream& os, WholeNumbers& rhs)
{
	ListIterator<int> it = rhs.numbersList.begin();


	return os;
}


but it would compile if I did this.
1
2
3
4
5
6
7
8
9
10
ostream& operator<<(ostream& os, WholeNumbers& rhs)
{

	ListIterator<int> it = rhs.numbersList.begin();
	cout << *it;


	
	return os;
}


Why does my operator NEED a cout to work. I figured operators ought to be overloaded to do absolutely anything I want them too. Responses greatly appreciated.
Hi everyone, I'm kinda confused what cout does that suddenly makes my overloaded "<<" function work.

Nothing.


Why does my operator NEED a cout to work.

It doesn't.

I would guess you made some other inadvertent change that caused the code not to compile. Supplying the specific errors generated by the compiler instead of saying "it wouldn't compile" would be helpful.

In your first function, please note that you are doing almost nothing. You should be using your "os" variable (the one you get by reference).

Something like this?

1
2
3
4
5
6
std::ostream& operator<<(std::ostream& os, WholeNumbers& rhs)
{
    for (ListIterator<int> it = rhs.numbersList.begin(); it != rhs.numbersList.end(); ++it)
        os << *it << ' ';
    return os;
}

This code prints all elements from rhs.numbersList into os.
Note that, when you do "cout<<myWholeNumbers;", os is an alias for cout. Do not explicitly use cout in here, anyways.
If you use file streams, you want to print the data to file, not to the console.
Topic archived. No new replies allowed.