错误:与 std::cout 中的运算符<<不匹配(我已经重载了 << 运算符)

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

本文关键字:运算符 重载 不匹配 错误 std cout      更新时间:2023-10-16

所以在做这个作业时,我卡住了,因为我得到了这个错误。我以前做过运算符重载,所以这令人惊讶。

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

这是主要的

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

所以出现上述错误,似乎找不到问题所在。任何帮助将不胜感激。

我相信

您的声明和定义之间存在不匹配。您的声明需要RGB& color,而您的定义需要const RGB& color。尝试像这样声明operator <<

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

您提供的声明是

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

您提供的定义是

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

注意到区别了吗?