如何用参数重载“=”运算符?

How overload the '=' operator with arguments?

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

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 个参数覆盖“=”运算符。

重载 = 运算符时,您只想在参数中包含右侧的值。由于您重载了 () 运算符,因此不需要使用 = 运算符处理 rc 值。您可以只使用 mt(2,4) = 3.5; 并且重载的 () 运算符将处理 mt(2,4) 部分。然后,您可以将 returned 数据设置为您想要的值,而无需重载任何 = 运算符。

您需要 return 对数据的引用才能对其进行编辑,但是:

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