MartinYakuza
MartinYakuza

Reputation: 135

Arguments' order in overloaded operators in C++

I am coding a matrix calculator and I wanted it to calculate operations like: 2*A, A*3 (where A is a matrix). So, I wrote this:

matrix operator* (double x , matrix mat)
{
    matrix temp(mat.n);

    for (int i = 0; i < mat.n; ++i)
        for (int j = 0; j < mat.n; ++j)
            temp.t[i][j] = mat.t[i][j] * x;

    return temp;
}

matrix operator* (matrix mat, double x)
{
    matrix temp(mat.n);

    for (int i = 0; i < mat.n; ++i)
        for (int j = 0; j < mat.n; ++j)
            temp.t[i][j] = mat.t[i][j] * x;

    return temp;
}

(matrix is the name of class, n is the size (matrixes are square), t is a static, 2-dimensional array t[n][n])

As you can see I coded 2 completely identical functions, where the only difference is the order of arguments. Is there any way to merge them into one? Other than converting x to diagonal matrix and multiplying them as 2 matrices.

(btw it's my first post on this forum, so please, don't be too harsh to me for asking such trivial question)

Upvotes: 1

Views: 127

Answers (1)

Alan Birtles
Alan Birtles

Reputation: 36419

Just make one function call the other:

matrix operator* (double x , matrix mat)
{
    matrix temp(mat.n);

    for (int i = 0; i < mat.n; ++i)
        for (int j = 0; j < mat.n; ++j)
            temp.t[i][j] = mat.t[i][j] * x;

    return temp;
}

matrix operator* (matrix mat, double x)
{
    return x * mat;
}

Upvotes: 1

Related Questions