DEV Community

Cover image for ++ Operator Overloading for a Matrix using Friend function in C++
Yash Desai
Yash Desai

Posted on

++ Operator Overloading for a Matrix using Friend function in C++

Define a class named "Matrix"

#include <iostream>
using namespace std;

class Matrix
{
private:
    int numbers[3][3];

public:
    void setNumbers(int n[][3]);
    void getNumbers();

    friend Matrix operator++(Matrix);
};
Enter fullscreen mode Exit fullscreen mode

Implement void setNumbers(int n[][3])

void Matrix::setNumbers(int n[][3])
{
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            numbers[i][j] = n[i][j];
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Implement void getNumbers()

void Matrix::getNumbers()
{
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            cout << numbers[i][j] << "\t";
        }
        cout << endl;
    }
    cout << endl;
}
Enter fullscreen mode Exit fullscreen mode

Implement Matrix operator++(Matrix n)

Matrix operator++(Matrix n)
{
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            n.numbers[i][j] = ++(n.numbers[i][j]);
        }
    }
    return n;
}
Enter fullscreen mode Exit fullscreen mode

Implement int main()

int main()
{

    Matrix matrix;
    int numbers[3][3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9},
    };

    matrix.setNumbers(numbers);
    matrix.getNumbers();

    matrix = ++matrix;

    matrix.getNumbers();

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Available on YouTube

Top comments (1)

Collapse
 
dynamicsquid profile image
DynamicSquid

Couldn't you do:

n.numbers[i][j] = ++(n.numbers[i][j]);

++(n.numbers[i][j]);
Enter fullscreen mode Exit fullscreen mode