1  #include <iomanip>
 2  #include "matrix2.h"
 3  
 4  Matrix::Matrix(int r, int c)
 5     : rows(r), columns(c), elements(new double[rows * columns])
 6  {
 7     for (int i = 0; i < rows * columns; i++)
 8        elements[i] = 0;
 9  }
10     
11  Matrix& Matrix::operator=(const Matrix& other)
12  {
13     if (this != &other)
14     {
15        free();
16        copy(other);
17     }
18     return *this;
19  }
20  
21  void Matrix::copy(const Matrix& other)
22  {
23     rows = other.rows;
24     columns = other.columns;
25     elements = new double[rows * columns];
26     for (int i = 0; i < rows * columns; i++)
27        elements[i] = other.elements[i];
28  }
29  
30  Matrix& Matrix::operator+=(const Matrix& right)
31  {
32     assert(rows == right.rows && columns == right.columns);
33     for (int i = 0; i < rows; i++)
34        for (int j = 0; j < columns; j++)
35           (*this)(i, j) += right(i, j);
36     return *this;
37  }
38  
39  Matrix operator+(const Matrix& left, const Matrix& right)
40  {
41     Matrix result = left;
42     result += right;
43     return result;
44  }
45     
46  Matrix operator*(const Matrix& left, const Matrix& right)
47  {
48     assert(left.get_columns() == right.get_rows());
49     Matrix result(left.get_rows(), right.get_columns());
50     for (int i = 0; i < left.get_rows(); i++)
51        for (int j = 0; j < right.get_columns(); j++)
52           for (int k = 0; k < left.get_columns(); k++)         
53              result(i, j) += left(i, k) * right(k, j); 
54     return result;
55  }
56     
57  Matrix operator*(const Matrix& left, double right)
58  {
59     Matrix result(left);
60     for (int i = 0; i < result.get_rows(); i++)
61        for (int j = 0; j < result.get_columns(); j++)
62           result(i, j) *= right; 
63     return result;
64  }
65     
66  ostream& operator<<(ostream& left, const Matrix& right)
67  {
68     const int WIDTH = 10;
69     for (int i = 0; i < right.get_rows(); i++)
70     {
71        for (int j = 0; j < right.get_columns(); j++)
72           left << setw(WIDTH) << right(i, j);
73        left << "\n";
74     }
75     return left;
76  }
77