SmallChess
SmallChess

Reputation: 8127

Why my operator overloading not compiling?

I have this member function

std::ostream& operator<<(std::ostream &stream) const

in Histogram<T>.

then in another class I have

static void write(const RGBHistogram<T> &hist, Output &output)
{
    std::cout << hist.redHist << std::endl;
}

redHist, greenHist and blueHist are Histogram.

Why it complains that no operator found which takes a right-hand operand of type Histogram?

Upvotes: 1

Views: 118

Answers (2)

Luchian Grigore
Luchian Grigore

Reputation: 258618

Operator << has to be implemented as a free function to be meaningful:

//inside class definition
//still free function
friend std::ostream& operator<<(std::ostream &, const Histogram &) 
{
}

Alternatively, you can define it outside the class. (I prefer it like this since it groups together class functionality)

Upvotes: 6

MarsRover
MarsRover

Reputation: 440

You should pass referece of you class and it should be friend not member function.

friend std::ostream& operator<<(std::ostream &ostream, const RGBHistogram<T> &stream)
{

  // do something.
  return ostream;
}

Upvotes: 5

Related Questions