#include<iostream>
#include<stdlib.h>
using namespace std;
class CMatrix
{
public:
CMatrix(int,int);
~CMatrix(){};
bool initialize(int,int);
bool create();
void output();
CMatrix operator +(CMatrix &M2);
CMatrix operator -(CMatrix &M2);
CMatrix operator *(int &m);
CMatrix operator *(CMatrix &M2);
private:
int m_row;
int m_col;
double *m_pData;
};
CMatrix::CMatrix(int r,int c)
{
initialize(r,c);
}
bool CMatrix::initialize(int r,int c)
{
m_row=r;
m_col=c;
m_pData=new double[r*c];
for(int i=0;i<m_row*m_col;i++)
{
m_pData[i]=0;
}
return true;
}
//输入矩阵数据元素,创建新矩阵
bool CMatrix::create()
{
for(int i=0;i<m_row*m_col;i++)
{
cin>>m_pData[i];
}
return true;
}
//矩阵输出函数
void CMatrix::output()
{
int j=0;
for(int i=0;i<m_row*m_col;i++)
{
cout<<m_pData[i]<<" ";
j++;
if(j==m_col) {j=0;cout<<"\n";}
}
}
//重载矩阵相加运算
CMatrix CMatrix::operator +(CMatrix &M2)
{
CMatrix M=*this;
for(int i=0;i<m_row*m_col;i++)
M.m_pData[i]=m_pData[i]+M2.m_pData[i];
return M;
}
//重载矩阵相减运算
CMatrix CMatrix::operator -(CMatrix &M2)
{
CMatrix M=*this;
for(int i=0;i<m_row*m_col;i++)
M.m_pData[i]=m_pData[i]-M2.m_pData[i];
return M;
}
//重载矩阵与常数相乘运算
CMatrix CMatrix::operator *(int &m)
{
CMatrix M=*this;
for(int i=0;i<m_row*m_col;i++)
M.m_pData[i]=m_pData[i]*m;
return M;
}
//重载矩阵与矩阵乘法运算
CMatrix CMatrix::operator *(CMatrix &M2)
{
CMatrix M=*this;
int j=0;
for(int i=0;i<m_row*m_col;i++)
{
M.m_pData[i]=m_pData[i]*M2.m_pData[i+j*m_col];
j++;
if(j==M2.m_row) j=0;
}
return M2;
}
|