简体   繁体   中英

Error: no match for operator << in std::cout (I have already overloaded the << operator)

So while working on this assignment I got stuck because I got this error. I have done operator overloading before so this came as a surprise.

class RGB
{
public:

    RGB(float r1, float g1, float  b1);
    RGB(RGB const& color); //copy constructor
    RGB();

    friend ostream& operator<<(ostream& os, RGB& color);
    friend istream& operator>>(istream& is, RGB& color);

    friend float r();
    friend float g();
    friend float b();
private:
    float r, g, b;
};

//Something something

RGB::RGB(float r1, float g1, float b1){
    r = r1;
    g = g1;
    b = b1;
}

//Something something

ostream& operator<<(ostream& os, const RGB& color){    // << Overloading
    return os<<"Red: "<<color.r<<endl<<"Green: "<<color.g<<endl<<"Blue: "<<color.b<<endl;
}

And this is in main

int main()
{
    RGB mycolor(1,2,3);
    cout<<mycolor;

return 0;
}

So the aforementioned error appears, can't seem to find what's wrong. Any help would be appreciated.

I believe there is a mis-match between your declaration and definition. You declaration takes a RGB& color while your definition takes a const RGB& color . Try to declare operator << like this:

friend ostream& operator<<(ostream& os, const RGB& color);

The declaration you've provided is

friend ostream& operator<<(ostream& os, RGB& color);

And the definition you've provided is

ostream& operator<<(ostream& os, const RGB& color)
//                               ^^^^^

Notice the difference?

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