matrix2.cpp.html

来自「《Big C++ 》Third Edition电子书和代码全集-Part1」· HTML 代码 · 共 82 行

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

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?