How do I properly overload << ?

The code below is what I have now, but g++ won't compile it, and I have no idea what to do.

1
2
3
4
5
6
7
8
9
ostream& Board::operator<<(ostream &output, const Board outBoard[9][9]){
	for (int i = 0; i<9; i++) {
		for (int j = 0; j<9; j++) {
			out << '|' << outBoard[i][j];
		} out << '|' << endl;
		out << "__________" << endl;
	}
	 return out;
 }
Try this instead:

ostream& Board::operator<<(ostream &output, const Board** outBoard)
Your Board class should not be an array... it should have an array, but it should not be an array...
1
2
3
4
5
6
7
8
9
10
11
12
class Board
  {
  ...
  private:
    Cell _cells[ 9 ][ 9 ];
  };

ostream& operator << ( ostream& outs, const Board& board )
  {
  ...
  return outs;
  }

Hope this helps.
Thanks, you are completely right about the array. That is how I implemented it; I just wasn't paying attention. However, I am still getting the exact same error:

Board.cpp:52: error: ‘std::ostream& Board::operator<<(std::ostream&, const Board**)’ must take exactly one argument
This should be a global funciton, not a member function.

If you need to access private/protected members of Board, then you can make it a friend function.
Last edited on
I have it as a friend function... I am just going to post the code (this is from the same project):

from Square.h:
1
2
3
4
public:
	Square();
	~Square();
	friend ostream& operator<<(ostream &output, const Square outSquare);


from Square.cpp
1
2
3
4
ostream& operator<<(ostream &output, const Square outSquare){
	output << outSquare.m_Solution;
	return output;
}


This will not compile. It is telling me the following

g++ -c Square.cpp
In file included from Square.cpp:10:
Square.h:21: error: ISO C++ forbids declaration of ‘ostream’ with no type
Square.h:21: error: ‘ostream’ is neither function nor member function; cannot be declared friend
Square.h:21: error: expected ‘;’ before ‘&’ token
Square.h: In function ‘std::ostream& operator<<(std::ostream&, Square)’:
Square.h:35: error: ‘int Square::m_Solution’ is private
Square.cpp:111: error: within this context
make: *** [Square.o] Error 1
The compiler doesn't know what an 'ostream' is, because you forgot to #include <iostream>.
Also, pass your square as a const reference.
1
2
3
4
5
6
7
#include <iostream>

class Square
{
	...
	friend std::ostream& operator<<( std::ostream&, const Square& );
};
1
2
3
4
5
6
7
#include "Square.h"
using namespace std;

ostream& operator<<( ostream& output, const Square& square )
{
	return output << square.m_Solution;
}

Hope this helps.
Thanks a lot!
Topic archived. No new replies allowed.