1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
|
#include <iostream>
#include <iomanip> //whitespaces in output (table)
class Matrix
{
private:
int rows, cols;
double* mArr;
public:
Matrix(int irows, int icols); //initialise
~Matrix(); //deconstructor
Matrix(Matrix &m); //copyconstructor
int getrows();
int getcols();
double& operator()(int inrows, int incols);
Matrix& operator=(Matrix& m);
};
Matrix::~Matrix() {
delete [] mArr;
}
Matrix::Matrix(int irows, int icols) {
rows = irows;
cols = icols;
// Function -> 2-D Array to 1D
mArr = new double[rows * cols];
for (int i=0;i<rows*cols;i++) mArr[i] = 0;
}
double& Matrix::operator()(int inrows, int incols)
{
// Array is linewise in rom
return mArr[inrows-1 + rows * (incols-1)];
}
Matrix::Matrix(Matrix &m)
{
cols = m.cols;
rows = m.rows;
mArr = new double[rows * cols];
for (int cpy=0;cpy<(m.getcols()*m.getrows());cpy++)
{
mArr[cpy]=m.mArr[cpy];
}
}
int Matrix::getrows()
{
return rows;
}
int Matrix::getcols()
{
return cols;
}
// operators
Matrix& Matrix::operator=(Matrix& m)
{
if (this == &m) return *this;
for(int i=1;i<=rows;i++) {
for(int j=1;j<=cols;j++) {
(*this)(i,j)=m(i,j);
}
}
return *this;
}
Matrix operator+(Matrix& a, Matrix& b)
{
Matrix c(a.getrows(),a.getcols());
for (int i=1;i<=a.getrows();i++){
for (int j=1;j<=a.getcols();j++){
c(i,j)=a(i,j)+b(i,j);
}
}
return c;
}
int main()
{
Matrix a(2,2),b(2,2),c(2,2);
a(1,1)=5;
a(1,2)=8;
a(2,1)=9;
a(2,2)=4;
b(1,1)=10;
b(1,2)=12;
b(2,1)=15;
b(2,2)=1;
c=a+b;
std::cout << "matrix c is:" << std::endl;
for (int k=1;k<=c.getrows();k++)
{
for (int i=1;i<=c.getcols();i++)
{
std::cout << std::setw(14) << c(k,i);
}
std::cout << std::endl;
}
return 0;
}
|