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);
};
``````

### 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];
}
}
}
``````

### 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;
}
``````

### 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;
}
``````

### 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;
}
``````

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