I am working on an exercise in operator overloading. I’ve created a matrix class and I am supposed to overload operators so I can do arithmetic on matrices efficiently.
My directions say that I am supposed to make two matrix arrays using the class constructor that has 2 parameters and a third matrix array that will be used to store the result of arithmetic using the default constructor (1 parameter).
Since I am going to use these arrays to overload operators they are going to need to be data members of the class (I think). However, I thought that classes were supposed to be as representative of real life things as possible so making a matrix class with multiple arrays doesn’t make sense to me (a matrix is only one matrix).
Am I misunderstanding classes or is there a different way to make additional matrices using the class constructor I am not thinking of? Thanks all, here is the code in question.
class matrix
{
friend ostream& operator << (ostream&, const matrix&); // << overloader
private:
int size // size indicates length of rows and cols, so size 3 means a 3 x 3 matrix
int array[10][10];
public:
matrix(int);
matrix(int, int);
};
matrix:: matrix (int sizeIn) //default constructor, use to make result matrix
{
int MAX_SIZE = 10;
if (0 > sizeIn && sizeIn > 10)
{
size = MAX_SIZE;
}
else
{
size = sizeIn;
}
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
array[i][j] = 0;
}
matrix:: matrix (int sizeIn, int rangeIn) //use to make first 2 matrices that will be added
{
int range;
int MAX_SIZE = 10;
int MAX_RANGE = 20;
if (0 > sizeIn && sizeIn > 10)
{
size = MAX_SIZE;
}
else
{
size = sizeIn;
}
if (0 > rangeIn && rangeIn > 20)
{
range = MAX_RANGE;
}
else
{
range = rangeIn;
}
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
array[i][j] = (rand() % (2 * range + 1) - range); //random number for each index
}
ostream & operator << (ostream & os, const matrix & arrayPrint) // << overloader
{
for (int i = 0; i < arrayPrint.size; i++)
{
cout << '|';
for (int j = 0; j < arrayPrint.size; j++)
{
os << setw(4) << arrayPrint.array[i][j] << " ";
}
os << setw(2) << '|' << endl;
}
return os;
}
You are misunderstanding the question. You are required to make a Matrix class that has 1 two dimensional array and then use the constructor to make two different matrices and then add them and store the result into a third one. So you will end up with something like this
Then you will make two matrices A and B as follows
You will then overload the = operator and + operator to let you do the following (of course you need to check if the sizes allow the operation first)
To overload the “=” operator