有两个矩阵a和b,均为2行3列。求两个矩阵之和。重载运算符“+”使之能用于矩阵相加。如何写出程序?
#include
#include
using namespace std;
class jz;
istream &operator>>(istream &is,jz &c);
ostream &operator<<(ostream &os,jz &c);
class jz
{
public:
jz(){};
friend jz operator+(const jz &a, const jz &b); //friend
friend ostream &operator<<(ostream &,jz &);
friend istream &operator>>(istream &,jz &);
jz(int a,int b,int c,int d,int e,int f)
{d1=a;d2=b;d3=c;d4=d;d5=e;d6=f;}
private:
int d1,d2,d3,d4,d5,d6;
};
ostream & operator<<(ostream &output,jz &c)
{
output<<c.d1<<" p="" ?
#include
//using namespace std;
class matrix
{
public:
matrix(){};
matrix(int array[3][3])
{
for(int i = 0; i < 3; i++)
for(int j = 0; j < 3; j++)
a[i][j] = array[i][j];
}
friend matrix operator + (matrix &,matrix &);
friend istream & operator >> (istream &input, matrix
&);
friend ostream & operator << (ostream &output, matrix
&);
private:
int a[3][3];
};
matrix operator + (matrix & m1, matrix & m2)
{
int array[3][3];
for(int i = 0; i < 3; i++)
for(int j = 0; j < 3; j++)
array[i][j] = m1.a[i][j] + m2.a[i][j];
return matrix(array);
}
ostream & operator << (ostream & output, matrix & m)
{
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
output<<m.a[i][j];< p="">
}
return output;
}
istream & operator >> (istream & input, matrix & m)
{
for(int i = 0; i < 3; i++)
for(int j = 0; j < 3; j++)
input>>m.a[i][j];
return input;
}
void main()
{
matrix m, m1,m2;
cout<<"输入第一个数组:"<<endl;< p="">
cin>>m1;
cout<<"输入第二个数组:"<<endl;< p="">
cin>>m2;
m = m1 + m2;
cout<<"两数组相加后结果:"<<endl;< p="">
cout<<m;< p="">
}