如何使用参数重载'='运算符?

joa*_*dre 3 c++ templates overriding class operators

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

MyClass<float> mt;
mt(2,4) = 3.5;
Run Code Online (Sandbox Code Playgroud)

我试过了:

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; 
};
Run Code Online (Sandbox Code Playgroud)

但编译器告诉我,我可以使用1参数覆盖'='运算符.

Jac*_*jes 10

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

您需要返回对数据的引用,以便您可以编辑它:

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