C++矩阵类重载运算符

2018-12-06 18:13

C++数据与结构第三次作业

潘隆武 21425202 机械工程

题目:在已建立N*M的矩阵类前提下,重载运算符“+”、“*”、“=”、“<<”、“>>”。

#include #include using namespace std;

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>m.pt[i][j]; } } return input; }

//对\进行重载,使它具有输出矩阵的功能 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


C++矩阵类重载运算符.doc 将本文的Word文档下载到电脑 下载失败或者文档不完整,请联系客服人员解决!

下一篇:中考语文句子衔接与排序复习专题含答案

相关阅读
本类排行
× 注册会员免费下载(下载后可以自由复制和排版)

马上注册会员

注:下载文档有可能“只有目录或者内容不全”等情况,请下载之前注意辨别,如果您已付费且无法下载或内容有问题,请联系我们协助你处理。
微信: QQ: