C++ 结构运算符重载
我有一个用于存储rgb值的结构。我重载了rgb和标量操作的常用运算符+、-、*C++ 结构运算符重载,c++,struct,C++,Struct,我有一个用于存储rgb值的结构。我重载了rgb和标量操作的常用运算符+、-、* struct rgb { float r; float g; float b; rgb() : r(0.f), g(0.f), b(0.f) {} rgb( const float& rr, const float& gg, const float& bb ): r(rr), g(gg), b(bb) {} rgb( const float&a
struct rgb {
float r;
float g;
float b;
rgb() : r(0.f), g(0.f), b(0.f) {}
rgb( const float& rr, const float& gg, const float& bb ): r(rr), g(gg), b(bb) {}
rgb( const float& f ): r(f), g(f), b(f) {}
rgb& operator +(const rgb& a) {
rgb t;
t.r = this->r + a.r;
t.g = this->g + a.g;
t.b = this->b + a.b;
return t;
}
rgb& operator +(const float& a) {
rgb t;
t.r = this->r + a;
t.g = this->g + a;
t.b = this->b + a;
return t;
}
rgb& operator -(const rgb& a) {
rgb t;
t.r = this->r - a.r;
t.g = this->g - a.g;
t.b = this->b - a.b;
return t;
}
rgb& operator -(const float& a) {
rgb t;
t.r = this->r - a;
t.g = this->g - a;
t.b = this->b - a;
return t;
}
rgb& operator *(const rgb& a) {
rgb t;
t.r = this->r * a.r;
t.g = this->g * a.g;
t.b = this->b * a.b;
return t;
}
rgb& operator *(const float& a) {
rgb t;
t.r = this->r * a;
t.g = this->g * a;
t.b = this->b * a;
return t;
}
float sum() {
return r + g + b;
}
};
在以下函数中使用此结构时,会得到意外的输出:
inline void foo(rgb &N,
rgb &X,
rgb &P,
rgb &R) {
float d = 0.0;
rgb d_v;
//find the dot product between N and (P-X)
d_v = N * (P - X); //this is always 0, 0, 0
d = d_v.sum();
R = P - N * d;
}
但是,如果我使用中间rgb存储中间操作,它可以正常工作:
inline void subspaceProjectCPU(rgb &N,
rgb &X,
rgb &P,
rgb &R) {
float d = 0.0;
rgb d_v;
rgb PX = P - X;
//find the dot product between N and (P-X)
d_v = PX * N;
d = d_v.sum();
rgb Nd = N*d;
R = P - Nd;
}
有人能解释一下吗?(我知道我没有在两边处理标量操作,所以定义了N*d,但没有定义d*N,其中N是rgb,d是float)。操作符函数返回对局部变量的引用,一旦操作符函数返回,该局部变量将不复存在。不要那样做;这是未定义的行为。只需返回一个
rgb
值。运算符+
,-
,*
,/
等不应返回引用。那个参考文献到底指的是什么?改为按值返回。看看如果你重载了一个操作符@
,你也应该重载@=
。