我是靠谱客的博主 彩色大象,这篇文章主要介绍定义Matrix类,为该类提供各种功能定义Matrix类需要用到动态开辟二维数组,现在分享给大家,希望可以做个参考。

定义Matrix类,为该类提供各种功能

定义Matrix类需要用到动态开辟二维数组

//动态开辟数组

复制代码
1
2
3
4
5
6
7
element = new int *[row]; for (int i = 0; i < row; i++) { element[i] = new int[col]; }

Matrix类的定义

复制代码
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
class Matrix { > private: > int row, col; > int **element = NULL; > public: > static int number; > Matrix()//构造 > { > cout<<"请输入矩阵的行数"<<endl; > cin>>row; > cout<<"请输入矩阵的列数"<<endl; > cin>>col; > > //动态开辟数组 > element = new int *[row]; > > for (int i = 0; i < row; i++) > { > element[i] = new int[col]; > } > > Matrix::number++; > } > > Matrix (const Matrix &a)//拷贝构造 > { > for(int i=0;i<a.row;i++) > { > for(int j=0;j<a.col;j++) > element[i][j]=a.element[i][j]; > } > } > Matrix& operator=(const Matrix &rhs)//赋值 > { > for(int i=0;i<rhs.row;i++) > { > for(int j=0;j<col;j++) > element[i][j]=rhs.element[i][j]; > } > return *this; > } > Matrix operator+(const Matrix &b)//加法 > { > Matrix temp; > for(int i=0;i<b.row;i++) > { > for(int j=0;j<b.col;j++) > temp.element[i][j]=this->element[i][j]+b.element[i][j]; > } > return temp; > } > ~Matrix() > { > for (int i = 0; i < row; i++) > { > delete []element[i]; > element[i] = NULL; > } > delete []element; > } > > friend Matrix operator-(const Matrix &a,const Matrix &b); > friend istream& operator>>(istream &cin,Matrix &rhs); > friend ostream& operator<<(ostream &cout,const Matrix &r); }; int Matrix::number=0; > Matrix operator-(const Matrix &a,const Matrix &b)//减法 > { > Matrix temp; > for(int i=0;i<a.row;i++) > { > for(int j=0;j<a.col;j++) > temp.element[i][j]=a.element[i][j]-b.element[i][j]; > } > return temp; > } > istream& operator>>(istream &cin,Matrix &rhs) > { > cout<<"请输入矩阵"<<endl; > > for (int i = 0; i < rhs.row; i++) > { > for (int j = 0; j < rhs.col; j++) > { > cin>>rhs.element[i][j]; > } > } > return cin; > } > ostream& operator<<(ostream &cout,const Matrix &r) > { > //输出数组 > cout<<"输出矩阵"<<endl; > > for (int i = 0; i < r.row; i++) > { > for (int j = 0; j < r.col; j++) > { > cout<<r.element[i][j]; > } > cout<<endl; > } > return cout; > } > > int main() { > Matrix a,b,c,d; > cin>>a; > cout<<a; > cin>>b; > cout<<b; > c=a+b; > cout<<c; > d=a-b; > cout<<d; > cout<<"number="<<Matrix::number<<endl; }

运行结果
在这里插入图片描述

参考资料:
1.https://blog.csdn.net/weixin_41966991/article/details/79994356

最后

以上就是彩色大象最近收集整理的关于定义Matrix类,为该类提供各种功能定义Matrix类需要用到动态开辟二维数组的全部内容,更多相关定义Matrix类内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(59)

评论列表共有 0 条评论

立即
投稿
返回
顶部