Home > Blockchain >  Is it possible to create a pointer to an object of a class that contains overloaded operator?
Is it possible to create a pointer to an object of a class that contains overloaded operator?

Time:06-01

I have some questions. I created a class that contains operator overloading:

double MMatrix::operator()(int i, int j)const
{
    return A[j   i * nCols];
}

To Pass an instance of that class to a function efficiently, I used to create a pointer of that class as the function formal parameter. And I want to use this overloaded operator in such a pointer to the class object within that function:

void Set_Matrix(MMatrix* M)
{
    size_t m = M->NRows();
    size_t n = M->NCols();
    for (unsigned int i = 0; i < m; i  )
        M(i, i) = 2; //This line gives error

}

The last line in that function gives an error message: E0109 expression preceding parentheses of apparent call must have (pointer-to-) function type I would appreciate you if you give me the solution to this problem.

CodePudding user response:

The problem is that M is a pointer to MMatrix so you would first have to dereference that pointer to get the underlying object of type MMatrix and then use the overloaded operator() as shown below:

void Set_Matrix(MMatrix* M)
{
    size_t m = M->NRows();
    size_t n = M->NCols();
    for (unsigned int i = 0; i < m; i  )
//------vvvv----------------->dereference M first before using operator()
        (*M)(i, i) = 2;

}

Other option is to make the parameter to be of type MMatrix& as shown below:

//---------------------v---->lvalue reference
void Set_Matrix(MMatrix& M)
{
    size_t m = M.NRows();
    size_t n = M.NCols();
    for (unsigned int i = 0; i < m; i  )
//------v----------------->no need of dereferencing
        M(i, i) = 2;

}

Note also that the return type of opeartor() is double and not double&, and since we cannot assign to a built in type rvalue the above solutions will generate errors saying the same. To solve that you can make the return type double& which will allow us to do the assignment.

CodePudding user response:

Cleaner syntax if you pass as a reference

void Set_Matrix(MMatrix& M)
{
    size_t m = M.NRows();
    size_t n = M.NCols();
    for (unsigned int i = 0; i < m; i  )
        M(i, i) = 2; <<==

}

other siwes you need

void Set_Matrix(MMatrix* M)
{
    size_t m = M->NRows();
    size_t n = M->NCols();
    for (unsigned int i = 0; i < m; i  )
        (*M)(i, i) = 2; <<==

}
  • Related