matrix2.cpp.html
来自「《Big C++ 》Third Edition电子书和代码全集-Part1」· HTML 代码 · 共 82 行
HTML
82 行
<html>
<body>
<pre> 1 #include <iomanip>
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 < rows * columns; i++)
8 elements[i] = 0;
9 }
10
<font color="#009999">11 Matrix& Matrix::operator=(const Matrix& other)</font>
12 {
13 if (this != &other)
14 {
15 free();
16 copy(other);
17 }
18 return *this;
19 }
20
<font color="#009999">21 void Matrix::copy(const Matrix& other)</font>
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 }</font>
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</pre>
</body>
</html>
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?