Home > front end >  C custom assignment
C custom assignment

Time:04-27

I have the following code:

template<size_t rows, size_t cols>
class Matrix{
    std::array<int, rows * cols>  data;
public:
    int  operator()(size_t i, size_t j){
        return data[i * cols   j];
    }
//  ...code...
}

What is the best way to achieve this:

Matrix<1,1> a;
a(0, 0) = 0;

avoiding the lvalue required as left operand of assignment error?

CodePudding user response:

You can change the following line:

int  operator()(size_t i, size_t j){

To:

int & operator()(size_t i, size_t j){

Returning a refernce (L value reference to be precise) to the element in the Matrix will allow you to assign to it.

CodePudding user response:

You need to return the reference of the element from data like this:

// can change
int &operator()(size_t i, size_t j)
{
    return data[i * cols   j];
}

And every STL container includes a const function, for the cases like const Matrix &

// cannot change 
int operator()(size_t i, size_t j) const
{
    return data[i * cols   j];
}
  •  Tags:  
  • c
  • Related