C++表达式中的运算符重载

发布于 2024-11-15 23:13:07 字数 773 浏览 2 评论 0原文

我确信这个问题已经在某个地方得到了回答,但我不知道要搜索什么。

我有以下情况。我创建了一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我是有多爱你 2024-11-22 23:13:07

替换 Vector&右const Vector&对。

表达式 (e_x*u_c) 是一个右值,对非常量的引用不会绑定到右值。

此外,成员函数本身也应该标记为 const:

Vector Vector::operator+(const Vector& right) const
{
    return Vector(x + right.x, y + right.y, z + right.z);
}

double Vector::operator*(const Vector& right) const
{
    return this->scalar_product(right);
}

scalar_product 也必须标记为 const。 此处了解有关 const 正确性的更多信息。

Replace Vector& right with const 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:

Vector Vector::operator+(const Vector& right) const
{
    return Vector(x + right.x, y + right.y, z + right.z);
}

double Vector::operator*(const Vector& right) const
{
    return this->scalar_product(right);
}

scalar_product will also have to be marked const. Read more about const correctness here.

千笙结 2024-11-22 23:13:07

这些声明是不正确的。

T T::operator +(const T& b) const;​

T T::operator *(const T& b) const;

C 和 C++ 中的运算符

The declarations aren't right.

T T::operator +(const T& b) const;​

T T::operator *(const T& b) const;

Operators in C and C++

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文