重载+/-运算符以添加/减去矢量

Overloading +/- operators to add/subtract vectors

本文关键字:添加 运算符 重载      更新时间:2023-10-16

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

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

我的+操作员为:

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&);

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

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();

但应该是常量:

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

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

现在,转到您的operator+:operator+可以是自由函数,也可以是成员函数。无论哪种方式,你都需要一个左手边和一个右手边。如果operator+是成员函数,则lhs总是this。因此,对于二进制+函数,您的声明如下:

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

请注意,参数由constref传递,函数本身是const,因此可以在const ThreeVector上调用它。

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

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

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

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

关于运算符+=的注意事项:标准约定是运算符+=、-=等返回对刚刚更改的对象的引用。return *this。你的功能应该看起来像:

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

+运算符中的左参数是对象本身,由"this"指针找到。它的成员可以像在任何其他成员函数中一样找到。所以你的+运营商应该被宣布为

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

最后一个常量表示左侧对象没有更改在5+2中,5或2被更改为创建7