用面向对象程序设计(OOP)方法实现一个基本矩阵类

2025-03-07 04:27:00
推荐回答(1个)
回答1:

#include
#include
#include

using namespace std;

//m*n 阶矩阵
class M
{
public:
M(int m, int n);
M(M& m);
virtual ~M();
int m;
int n;
private:
int *a;
friend istream& operator>>( istream& in, M& m );
friend ostream& operator<<( ostream& out, M& m );
friend M& operator+(M& a, M& b);
};

M::M(int m=1, int n=1) : m(m), n(n)
{
a = new int[n*m];
}

//拷贝构造
M::M(M& m) : m(m.m), n(m.n)
{
a = new int[m.n*m.m];
memcpy(a, m.a, m.n*m.m*sizeof(int));
}

M::~M()
{
delete a;
}

//输入矩阵
istream& operator>>( istream& in, M& m )
{
cout<<"input "< for( int i=0; i {
cout<<"input line "< for( int j=0; j {
in >> (*(m.a+i*m.n+j));
}
}
return in;
}

//输出矩阵
ostream& operator<<( ostream& out, M& m )
{
for( int i=0; i {
for( int j=0; j {
out< }
out< }

return out;
}

//矩阵加法
M& operator+(M& a, M& b)
{
if( !( a.m==b.m && a.n==b.n ) )
{
cout<<"Error: can not +"< }

M m(a);

for( int i=0; i {
for( int j=0; j {
*(m.a+i*m.n+j) += *(b.a+i*m.n+j);
}
}
M* x = new M(m);
return *x;
}

int main(int argc, char *argv[])
{
M a(2, 3), b(2, 3);
cin>>a>>b;
M c = a + b;
cout<
return 0;
}