Home > database >  C no match for ‘operator=’
C no match for ‘operator=’

Time:10-15

I've created a class to simulate the behavior of vector of int, because every time I read or write some value, also a read and write counter should be incremented to keep track of its usage. I can’t change the code in main.cpp other than from the type “int” to the type “MyInt”, that's why I'm trying to overload the [] operator to read inside the brackets and pass the operation to a second one, using a wrapper class. The error I got is:

no match for ‘operator=’ (operand types are ‘MyInt’ and ‘int’)

so it looks like that the intercept of the assignment of the wrapper class doesn't work. I've also overloaded the "new []" operator for the dynamic declaration and it seems to work properly. Any suggestion?

CodePudding user response:

In your code:

    V = new MyInt[10];

V is an array of MyInt, so when you're trying to access the third index by V[3], you're not calling the overloaded operator[] but accessing the third element of the array, you can do this and see that the type of elem is MyInt and not MyInt::wrapper:

auto elem = V[3];

You can simply solve this by:

    (*V)[3] = 3;
    // or
    V[0][3] = 3;

But this is a terrible way to make a vector, you should just use std::vector or re-design it.

CodePudding user response:

The problem is that the overloaded operator= that you've provided is for class wrapper and not MyInt. Now, the type of the expression V[3] is MyInt and since there is no MyInt::operator=, you get the mentioned error for V[3] = 8.

To solve this, change V[3] to (*V)[3] so that now, the type of the expression *V is MyInt and that of (*V)[3] is wrapper and since there is an MyInt::wrapper::operator= available, this will work.

  • Related