C++数据与结构第三次作业
潘隆武 21425202 机械工程
题目:在已建立N*M的矩阵类前提下,重载运算符“+”、“*”、“=”、“<<”、“>>”。
#include
class Matrix {
public: Matrix();//默认构造函数 Matrix(int ,int );//初始化构造函数 Matrix(const Matrix &);//拷贝构造函数 ~Matrix();//析构函数 Matrix operator+(Matrix &); Matrix operator*(Matrix &); Matrix operator=(Matrix &); friend istream & operator>>(istream &,Matrix &); friend ostream & operator<<(ostream &,Matrix &); private: int row; int column; double **pt; };
//主函数 int main() {
system(\ int r,c; Matrix temp1,temp2; cout<<\请输入矩阵M1的行数(N)和列数(M):\ cin>>r>>c; Matrix M1(r,c); cin>>M1; cout<<\请输入矩阵M2的行数(N)和列数(M):\ cin>>r>>c; Matrix M2(r,c); cin>>M2; cout<<\=======\ cout<<\
cout<<\ cout<<\=======\ cout<<\与M2的运算结果:\ temp1=M1+M2; temp2=M1*M2; cout<<\ cout<<\ return 0; }
//创建默认矩阵 Matrix::Matrix() { row=0; column=0; pt=NULL; }
//创建row行column列的矩阵,并将其初始化为零阵 Matrix::Matrix(int r,int c):row(r),column(c) { if(row<1||column<1) cout<<\矩阵的行数和列数都必须大于0!\ else { pt=new double*[row]; for(int i=0;i //拷贝构造函数,以矩阵A创建新矩阵B并以A对B进行初始化 Matrix::Matrix(const Matrix &m) { row=m.row; column=m.column; pt=new double*[row]; for(int i=0;i //析构函数,对堆中的动态空间进行释放 Matrix::~Matrix() { if(pt!=NULL) { for(int i=0;i //对\进行重载,使它具有输入矩阵的功能 istream & operator>>(istream &input,Matrix &m) { cout<<\请输入\个数作为矩阵元素:\ for(int i=0;i //对\进行重载,使它具有输出矩阵的功能 ostream & operator<<(ostream &output,Matrix &m) { for(int i=0;i output< //对\进行重载,使它具有将两个同型矩阵相加的功能 Matrix Matrix::operator+(Matrix &m) { Matrix temp; if(row!=m.row||column!=m.column) cout<<\矩阵M1和矩阵M2不是同类型矩阵,不能相加!\ else { temp.row=row; temp.column=column; temp.pt=new double*[temp.row]; for(int i=0;i temp.pt[i]=new double[temp.column]; for(int j=0;j return temp; } //对\进行重载,使它具有将两个符合相乘条件的矩阵相乘的功能 Matrix Matrix::operator*(Matrix &m) { Matrix temp; if(column!=m.row) cout<<\矩阵M1的列数和矩阵M2的行数不相等,不能相乘!\ else { temp.row=row; temp.column=m.column; temp.pt=new double*[temp.row]; for(int i=0;i double sum=0; for(int k=0;k return temp; } //对\进行重载,使它具有将一个矩阵赋给另一矩阵的功能 Matrix Matrix::operator=(Matrix &m) { row=m.row; column=m.column; pt=new double*[m.row]; for(int i=0;i