C++面向对象程序设计课程的作业,初学者,很多地方做的不好,欢迎指正。
题目要求:
定义矩阵类 Matrix,包含整数型私有成员变量 row 和 col,分别代表矩阵的行数和列数。矩阵元素存储于通过 new 操作符获取的一维数组,定义该类的构造函数、拷贝构造函数、析构函数(delete申请的堆资源),重载算术运算符+和*,使之实现矩阵加法和乘法运算;重载<<和>>运算符,使之能用于该矩阵的输入和输出。
#include<iostream>
using namespace std;
class Matrix
{
public:
Matrix() {}//构造函数
Matrix(int r,int c,int a[])//构造函数
{row=r;col=c;arr=a;}
Matrix(const Matrix &A)//拷贝构造函数
{row=A.row;col=A.col;arr=A.arr;}
~Matrix()//析构函数
{delete []arr;}//delete申请的堆资源
Matrix operator+(Matrix &A);//重载算术运算符+
Matrix operator*(Matrix &A);//重载算术运算符*
friend ostream & operator<<(ostream &,const Matrix &);//重载输出运算符<<
friend istream & operator>>(istream &,Matrix &);//重载输入运算符>>
private:
int row,col;//行数、列数
int *arr=new int[100];//矩阵元素
};
Matrix Matrix::operator+(Matrix &A)//重载算术运算符+,实现矩阵加法
{
int i,j;
Matrix res;
res.row=row;
res.col=col;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
res.arr[i*col+j]=arr[i*col+j]+A.arr[i*col+j];
}
}
return res;
}
Matrix Matrix::operator*(Matrix &A)//重载算术运算符*,实现矩阵乘法
{
int i,j,k,result=0;
Matrix res;
res.row=row;
res.col=A.col;
for(i=0;i<row;i++)
{
for(j=0;j<A.col;j++)
{
for(k=0;k<col;k++)
{
result+=arr[i*col+k]*A.arr[k*A.col+j];
}
res.arr[i*col+j]=result;
result=0;
}
}
return res;
}
ostream & operator<<(ostream & out,const Matrix &A)//重载运算符<<,实现矩阵输出
{
int i,j;
out<<A.row<<" ";
out<<A.col;
out<<endl;
for(i=0;i<A.row;i++)
{
for(j=0;j<A.col;j++)
{
out<<A.arr[i*A.col+j]<<" ";
}
out<<endl;
}
return out;
}
istream & operator>>(istream & in,Matrix &A)//重载运算符>>,实现矩阵输入
{
in>>A.row;
in>>A.col;
int i,j;
for(i=0;i<A.row;i++)
{
for(j=0;j<A.col;j++)
{
in>>A.arr[i*A.col+j];
}
}
return in;
}
int main()
{
//输出矩阵按照此格式:第一行两个数为行数、列数,第二行及以后为矩阵元素
Matrix x,y,sum,product;
cout<<"the pattern: \nrow col\nelements\n\nx:\n";
cin>>x;
cout<<"y:\n";
cin>>y;
sum=x+y;
product=x*y;
cout<<"x and y sum is "<<endl;
cout<<sum<<endl;
cout<<"x and y product is "<<endl;
cout<<product<<endl;
//delete申请的堆资源
x.~Matrix();
y.~Matrix();
sum.~Matrix();
product.~Matrix();
return 0;
}
运行结果: