我正在尝试为 AVR 项目编写一个 RGB 类。但是当我尝试使用它时,它在某些运算符上失败了。
Error 415 no match for 'operator*' (operand types are 'const float' and 'RGB') ...AnimationWallWall.cpp 321 18 Cube
下面是它的外观:
class RGB
{
//variables
public:
uint8_t r, g, b;
//functions
public:
RGB();
//assignment
RGB &operator=( const RGB &other );
RGB &operator+(const RGB &other);
RGB &operator* (const uint8_t &other);
RGB &operator* (const float &other);
//some more operators here
}; //RGB
和实现:
RGB::RGB(): r(0), g(0), b(0)
{
}
RGB &RGB::operator=( const RGB &other)
{
if(this != &other) //no self assignment
{
r = other.r;
g = other.g;
b = other.g;
}
//per convention return "yourself"
return *this;
}
RGB &RGB::operator+(const RGB &other)
{
r += other.r;
r %= MAX_COLOR_RGB;
g += other.g;
g %= MAX_COLOR_RGB;
b += other.b;
b %= MAX_COLOR_RGB;
//per convention return "yourself"
return *this;
}
RGB &RGB::operator*(RGB rgb, const uint8_t &i)
{
rgb.r *= i;
rgb.r %= MAX_COLOR_RGB;
rgb.g *= i;
rgb.g %= MAX_COLOR_RGB;
rgb.b *= i;
rgb.b %= MAX_COLOR_RGB;
//per convention return "yourself"
return *this;
}
RGB &RGB::operator*( const float &f, RGB rgb)
{
rgb.r *= f;
rgb.r %= MAX_COLOR_RGB;
rgb.g *= f;
rgb.g %= MAX_COLOR_RGB;
rgb.b *= f;
rgb.b %= MAX_COLOR_RGB;
return rgb;
}
RGB &RGB::operator*(const uint8_t &i, RGB rgb)
{
rgb.r *= i;
rgb.r %= MAX_COLOR_RGB;
rgb.g *= i;
rgb.g %= MAX_COLOR_RGB;
rgb.b *= i;
rgb.b %= MAX_COLOR_RGB;
//per convention return "yourself"
return rgb;
}
RGB &RGB::operator*(RGB rgb, const float &f)
{
rgb.r *= f;
rgb.r %= MAX_COLOR_RGB;
rgb.g *= f;
rgb.g %= MAX_COLOR_RGB;
rgb.b *= f;
rgb.b %= MAX_COLOR_RGB;
return rgb;
}
我正在尝试做的是(错误中的第 321 行):
RGB newColor;
newColor = v * m_color + (1 - v) * m_targetColor;
而V是一些价值[0,1]
.我做错了什么?
您的成员运算符
RGB &operator* (const float &other);
等效于非成员运算符:
RGB& operator* (RGB, float);
这将处理左手乘法:RGB() * float()
。您需要添加第二个非成员operator*
来处理右侧乘法:
RGB operator*(float, const RGB& );
请注意,operator*
应返回RGB
,而不是RGB&
,因为您当前返回的是对临时RGB
的引用。
您的二元运算符*
运算符重载(采用 RGB 类型的 rhs 值)应该是一个非成员函数,因为您已经重载了 RGB 的运算符,但该方法未为 float 定义
转换
RGB &RGB::operator*( const float &f, RGB rgb)
{
rgb.r *= f;
rgb.r %= MAX_COLOR_RGB;
rgb.g *= f;
rgb.g %= MAX_COLOR_RGB;
rgb.b *= f;
rgb.b %= MAX_COLOR_RGB;
return rgb;
}
到非成员函数
RGB operator*( const float &f,const RGB& rgb)
{
RGB _rgb = rgb;
_rgb = _rgb * f;
return _rgb;
}
并将以上作为朋友
注意
更好的设计是仅重载类的一元运算符,并使所有二进制运算符都为非成员。
RGB& RGB::operator*( const float &f)
{
r = (r * f) % MAX_COLOR_RGB;
g = (g * f) % MAX_COLOR_RGB;
b = (b * f) % MAX_COLOR_RGB;
return *this;
}
RGB operator*( const float &f,const RGB& rgb)
{
RGB _rgb = rgb;
_rgb = _rgb * f;
return _rgb;
}
RGB operator*( const RGB& rgb, const float &f)
{
RGB _rgb = rgb;
_rgb = _rgb * f;
return _rgb;
}