首页 > 解决方案 > 如何用参数重载“=”运算符?

问题描述

使用“=”为类成员设置一些值并提供其他参数的正确语法是什么?例如向量中的位置:

MyClass<float> mt;
mt(2,4) = 3.5;

我试过了:

template <class _type> 
_type myClass<_type>::operator()(int r,int c) {
    return data[r*nCols+c]; 
};

template <class _type>  
myClass<_type>::operator= (int r, int c, _type val) { 
    data(r,c) = val; 
};

但是编译器告诉我我可以用 1 个参数覆盖 '=' 运算符。

标签: c++classtemplatesoperatorsoverriding

解决方案


当您重载=运算符时,您只希望在参数中有右手值。由于您重载了()运算符,因此您不需要使用运算符处理randc=。您可以只使用mt(2,4) = 3.5;,重载的()运算符将处理该mt(2,4)部分。然后,您可以将返回的数据设置为您想要的值,而无需重载任何=运算符。

您需要返回对数据的引用,以便可以对其进行编辑,但是:

template <class _type>
_type& myClass<_type>::operator()(int r,int c) {
    return data[r*nCols+c]; 
};

推荐阅读