重载+/-运算符以添加/减去矢量
Overloading +/- operators to add/subtract vectors
我正在为一个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;
请注意,参数由const
ref传递,函数本身是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
相关文章:
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 运算符重载 (+),用于添加两个具有 C++ 的数组
- 运算符重载使用运算符+添加类模板
- 重载运算符与添加问题
- 运算符重载 += 添加新对象
- 为什么 C++ 11 在 ios 类中添加了运算符 bool
- C++ 尝试将>>运算符重载添加到模板
- 如何在自定义对象的<<运算符中添加自定义前缀
- oStream 不打印添加两个 valarray 的结果(使用运算符重载)
- 向日期运算符添加天数+
- 如何在三元条件运算符中添加换行符和连接? :在 C++ 中
- 重载加法运算符(使用函数向对象添加字符串)
- 有什么理由不扩展 std::set 以添加下标运算符吗?
- 赋值和添加运算符重载(2个表和int的串联)
- 实现矩阵类添加运算符重载奇怪的输出
- 复合赋值和添加运算符重载
- 当Type为unique_ptr时,为向量添加运算符[]
- 向 std::vector <T>添加运算符