错误:与 std::cout 中的运算符<<不匹配(我已经重载了 << 运算符)
Error: no match for operator << in std::cout (I have already overloaded the << operator)
所以在做这个作业时,我卡住了,因为我得到了这个错误。我以前做过运算符重载,所以这令人惊讶。
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)
// ^^^^^
注意到区别了吗?
相关文章:
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- <T> 通过模板化运算符重载将 std::complex 乘以双倍
- C++20概念:需要运算符重载
- 使用赋值运算符重载从类中返回jobject
- 在运算符重载定义中使用成员函数(const错误)
- 字节到位运算符重载C++
- 为什么在运算符重载时需要参考?
- 类中 c++ 的运算符 + 重载
- 算术复合运算符重载为非成员
- 运算符重载 (+),用于添加两个具有 C++ 的数组
- 交换运算符 + 重载会导致无限递归
- 如何理解新的运算符重载?
- 向量保持复数的运算符重载
- 如何创建运算符重载?
- 链接列表运算符重载没有打印出我想要的内容
- C++:需要帮助了解运算符重载错误
- 使用模板化运算符重载 XOR 运算符失败
- 如何确保接受的C++模板类型使运算符重载?
- 运算符重载使用运算符+添加类模板