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

标签 c++ expression overloading operator-keyword

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

我有以下情况。我创建了一个 Vector 类并重载了“*”(乘以 escalar)和“+”运算符(添加两个 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);
}

最佳答案

Vector& right 替换为 const Vector& right

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

此外,成员函数本身也应标记为 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 正确性的信息 here .

关于表达式中的 C++ 运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6377786/

相关文章:

c# - 创建可用作函数/方法的类型

postgresql - 是否可以使用子类型重载来配置函数?

c++ - 奇怪的 pthread_mutex_t 行为

c++ - 比较字符串的一部分

java - 2 的倍数的 boolean 表达式

c++ - 为什么这段代码会产生错误?

haskell - 重载 Haskell 中的内置函数

c++ - 寻求一种在 C++ 中设置 128 位或更高位的位集的方法

Visual Studio 2012 : LPCWSTR and wstring 中的 C++ 编译错误

java - 条件正则表达式搜索