【发布时间】:2018-12-07 19:13:30
【问题描述】:
我正在编写一个具有std::vector 作为成员的类,我希望能够使用默认运算符+/+=、*/*= 批量修改其数据等以标量为参数,例如
MyClass<float> obj;
obj += 4.0;
我正在尝试将运算符重载定义为:
template <class _type>
matrix2D<_type>& matrix2D<_type>::operator=(matrix2D<_type> _mat){
std::swap(_mat,*this);
return *this;
};
template <class _type>
template <typename _input_type>
myClass<_type> myClass<_type>::operator*(_input_type _val) {
for (int i = 0; i < data.size(); ++i) data[i] *= _val;
return *this;
};
template <class _type>
template <typename _input_type>
myClass<_type> myClass<_type>::operator*=(_input_type _val) {
for (int i = 0; i < data.size(); ++i) data[i] *= _val;
return *this;
};
我没有收到编译或运行时错误,但值保持不变。我尝试了多种不同类型的返回值(MyClass&、void)并将myClass 对象作为参数传递。我错过了什么?
【问题讨论】:
-
您似乎想要的已经以
std::valarray的形式存在。 -
由于您的问题的可能原因,赋值运算符应该返回
*this通过引用。而且您的operator*也是错误的,它不应该修改this或其成员。我建议你阅读例如this operator overloading reference,尤其是仔细看the canonical implementations。当然还有read a few good books。 -
据我所见,您的实例已被修改(即使是
operator*:-/ )。 -
我遵循here 中的指导方针。我试过通过引用返回类对象——结果是一样的。我不明白为什么我不应该修改
this? -
如果您有
a = b * c,是否应该修改b或c?不,这不是乘法(其他其他算术运算)的工作原理。
标签: c++ templates operator-overloading