C++表达式中的运算符重载
我确信这个问题已经在某个地方得到了回答,但我不知道要搜索什么。
我有以下情况。我创建了一个 Vector 类并重载了“*”(乘以标量)和“+”运算符(添加两个向量)。现在,下面的代码行:
Vector sum = (e_x*u_c) + (e_y*u_r);
这给了我以下错误:
error: no match for 'operator+' in '((Teste*)this)->Teste::e_x.Vector::operator*(u_c) + ((Teste*)this)->Teste::e_y.Vector::operator*(u_r)'
但是,如果我将此错误行替换为:
Vector aux = (e_x*u_c);
Vector aux2 = (e_y*u_r);
Vector sum = aux + aux2;
我根本没有得到任何错误。为什么?这两个表达式不是等价的吗?
编辑: 这是我对“*”和“+”的定义:]
Vector Vector::operator+(Vector& right)
{
return Vector(x + right.x, y + right.y, z + right.z);
}
double Vector::operator*(Vector& right)
{
return this->scalar_product(right);
}
I'm sure this has already been answered somewhere, but I don't know what to search for.
I have the following situation. I made a Vector class and overloaded the "*" (multiply by escalar) and the "+" operators (add two vectors). Now, the following line of code:
Vector sum = (e_x*u_c) + (e_y*u_r);
This gives me the following error:
error: no match for 'operator+' in '((Teste*)this)->Teste::e_x.Vector::operator*(u_c) + ((Teste*)this)->Teste::e_y.Vector::operator*(u_r)'
But, if I replace this error line by:
Vector aux = (e_x*u_c);
Vector aux2 = (e_y*u_r);
Vector sum = aux + aux2;
I get no errors at all. Why? Aren't those two expressions meant to be equivalent?
EDIT:
Here are my the definitions of "*" and "+":]
Vector Vector::operator+(Vector& right)
{
return Vector(x + right.x, y + right.y, z + right.z);
}
double Vector::operator*(Vector& right)
{
return this->scalar_product(right);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
替换
Vector&右
与const Vector&对。
表达式
(e_x*u_c)
是一个右值,对非常量的引用不会绑定到右值。此外,成员函数本身也应该标记为 const:
scalar_product 也必须标记为 const。 此处了解有关 const 正确性的更多信息。
Replace
Vector& right
withconst Vector& right
.The expression
(e_x*u_c)
is an rvalue, and references to non-const won't bind to rvalues.Also, the member functions themselves should be marked
const
as well:scalar_product
will also have to be markedconst
. Read more about const correctness here.这些声明是不正确的。
C 和 C++ 中的运算符
The declarations aren't right.
Operators in C and C++