简体   繁体   中英

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?

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)

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM