3

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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
joaocandre
  • 1,621
  • 4
  • 25
  • 42
  • 1
    `operator =` should assign one `MyClass` to another `MyClass`. If you want to assign to an element then access the element with your `operator()` like you do with `mt(2,4) = 3.5;` – NathanOliver Jun 27 '18 at 15:55
  • @NathanOliver it doesn't work, I get " error: lvalue required as left operand of assignment" – joaocandre Jun 27 '18 at 16:05
  • 1
    `operator=` has a very limited set of parameters it can take. Effectively there is one parameter, and it is the object being copied. Recommended reading: [What are the basic rules and idioms for operator overloading?](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading) – user4581301 Jun 27 '18 at 16:06

1 Answers1

10

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]; 
};
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Jacob Boertjes
  • 963
  • 5
  • 20