将 +/- 运算符重载到 add/subtract 向量

Overloading +/- operators to add/subtract vectors

我正在为一个 c++ 项目开发 class,我必须重载我的所有运算符才能处理向量。具体来说,我将向量定义如下:

template<class Type>
ThreeVector<Type>::ThreeVector(Type x, Type y, Type z) {
    mx=x;
    my=y;
    mz=z;
}

我的 +operator 是:

template<class Type>
ThreeVector<Type> operator+(const ThreeVector<Type>& v, const//
ThreeVector<Type>& w) {

    return ThreeVector<Type>(v)+=w;
}

我已经重载了 += 和 -= 运算符。但是,我不断收到此错误:

ThreeVT.cxx:12:26: error: no matching function for call to// 
‘ThreeVector<double>::ThreeVector(ThreeVector<double>)’
ThreeVector<double> d=c+a;

ThreeVector.h:141:29: error: no matching function for call to 
‘ThreeVector<double>::ThreeVector(const ThreeVector<double>&)’
 return ThreeVector<Type>(v)+=w;

如有任何帮助,我们将不胜感激!这个错误似乎无论我做什么都会出现,我不知道它在这种情况下的真正含义。

你有几个问题:

引用函数:

ThreeVector( ThreeVector&);
ThreeVector<Type> operator=( ThreeVector&);
ThreeVector<Type> operator+=( ThreeVector&);
ThreeVector<Type> operator-=( ThreeVector&);
ThreeVector<Type> operator-( ThreeVector&);

应该采用 const 引用,除非他们实际更改了参数:

ThreeVector(const ThreeVector&);
ThreeVector<Type> operator=(const ThreeVector&);
ThreeVector<Type> operator+=(const ThreeVector&);
ThreeVector<Type> operator-=(const ThreeVector&);
ThreeVector<Type> operator-(const ThreeVector&);

你的访问器函数是非常量的:

Type x();
Type y();
Type z();

但应该是const:

Type x() const;
Type y() const;
Type z() const;

所有这些更改都应在 class 主体和函数定义中进行。

现在,关于您的 operator+operator+ 可以是自由函数或成员函数。无论哪种方式,您都需要一个左侧和一个右侧。如果 operator+ 是一个成员函数,那么 lhs 总是 this。因此,对于二进制 + 函数,您的声明如下所示:

ThreeVector<Type> operator+(const ThreeVector& rhs) const;

注意参数是通过constref传递的,函数本身是const,所以可以在const ThreeVector.

上调用

您代码中的实现缺少 class 名称。它应该看起来像:

template<class Type>
ThreeVector<Type> ThreeVector<Type>::operator+(const ThreeVector<Type>& rhs) const

然后,函数体可以使用 this 关键字:

return ThreeVector<Type>(*this) += rhs;

关于 operator+= 的注意事项:标准约定是 operator+=、-= 等 return 对刚刚更改的对象的引用。 return *this。您的函数应如下所示:

ThreeVector<Type>& operator+=(const ThreeVector&);

+ 运算符的左参数是对象本身,由 "this" 指针找到。它的成员可以在任何其他成员函数中找到。所以你的 + 运算符应该声明为

const ThreeVector<Type> operator+(const ThreeVector<Type>& v) const;

最后一个const表示左边的对象没有改变 在 5 + 2 中,5 或 2 被修改为 7