Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How overload the '=' operator with arguments?

What would be the correct syntax to use the '=' to set some value to a class member and supply additional arguments? E.g. positions in a vector:

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

I've tried:

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; 
};

But the compiler tells me I can override the '=' operator with 1 argument.

like image 625
joaocandre Avatar asked Dec 17 '25 23:12

joaocandre


1 Answers

When you overload the = operator, you only want to have the right-hand value in the arguments. Since you overloaded the () operator, you don't need to handle the r and c value with the = operator. You can just use mt(2,4) = 3.5; and the overloaded () operator will handle the mt(2,4) portion. Then, you can just set the returned data to your desired value without overloading any = operator.

You need to return a reference to the data so you can edit it, however:

template <class _type>
_type& myClass<_type>::operator()(int r,int c) {
    return data[r*nCols+c]; 
};
like image 147
Jacob Boertjes Avatar answered Dec 20 '25 13:12

Jacob Boertjes