0
// For left scaler
Matrix operator*(int x , Matrix &m)
{
    Matrix Mul(m.get_rows(),m.get_cols());
    int **mul=Mul.get_matrix();
    int **mat = m.get_matrix();
    for (int i = 0; i < m.get_rows(); i++)
        for (int j = 0; j < m.get_cols(); j++)
            mul[i][j] = x * mat[i][j];
    return Mul;
}
// For right scaler
Matrix operator*(Matrix &m ,int x)
{
    Matrix Mul(m.get_rows(),m.get_cols());
    int **mul=Mul.get_matrix();
    int **mat = m.get_matrix();
    for (int i = 0; i < m.get_rows(); i++)
        for (int j = 0; j < m.get_cols(); j++)
            mul[i][j] = x * mat[i][j];
    return Mul;
}

Above is the code that multiply scaller with a matrix, there are two satiuations, the first one is scaller with the right (matrix * 5), the second one is scaller with the left (5 * matrix). Both the operator functions are overloaded for the perpuse,and they just works well, when i use them like so

//scaler to the left 
    result = 5 * m1;
    cout << result;
//scaler to the right
    result = m1 * 2;
    cout << result;

The question is the code in both the operator functions are excatly the same, so is there any better way to do this, in order to reuse the code.

Ali Niaz
  • 19
  • 3
  • Yeah, implement a single function and call it in both operators (or in one of the operators, call the other operator with the input parameters in opposite order). –  Oct 30 '22 at 07:09
  • This is **trivial**. Just use the one in the another. See duplicate: [Commutative operator overloading + of 2 different objects](https://stackoverflow.com/questions/3764604/commutative-operator-overloading-of-2-different-objects) – Jason Oct 30 '22 at 07:11
  • Refer to [how to ask](https://stackoverflow.com/help/how-to-ask) where the first step is to *"search and then research"* and you'll find plenty of related SO posts for this. – Jason Oct 30 '22 at 07:13

1 Answers1

1

the code in both the operator functions the code are excatly same, so is there any better way to do this, in order to reuse the code

You could let one of the overloads call the other:

Matrix operator*(int x, Matrix &m)
{
    Matrix Mul(m.get_rows(),m.get_cols());
    int **mul=Mul.get_matrix();
    int **mat = m.get_matrix();
    for (int i = 0; i < m.get_rows(); i++)
        for (int j = 0; j < m.get_cols(); j++)
            mul[i][j] = x * mat[i][j];
    return Mul;
}

Matrix operator*(Matrix &m, int x)
{
    return x * m; // using Matrix operator*(int x, Matrix &m)
}

I suggest that you also take the Matrix objects by const& since you are not changing them.

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108