Hi, 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.
#include <iostream>
#include <iomanip>
#include <ctime>
#include <cstdlib>
#include <cmath>
using namespace std;
class matrix
{
friend ostream& operator << (ostream&, const matrix&);
private:
int size;
int array[10][10];
public:
matrix(int);
matrix(int, int);
};
int main()
{
int sizeIn, rangeIn;
cout << "What size matrix would you like to generate?" << endl;
cin >> sizeIn;
cout << "What is the highest value you would like to allow a number in the matrix to be?" << endl;
cin >> rangeIn;
matrix arrayPrint(sizeIn, rangeIn);
srand (static_cast<int>(time(NULL)));
cout << arrayPrint << endl;
return 0;
}
matrix:: matrix (int sizeIn)
{
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)
{
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);
}
ostream & operator << (ostream & os, const matrix & arrayPrint)
{
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;
}