有两个矩阵a和b,均为3行4列。求两个矩阵之和。重载运算符“+”,使之能用于矩阵相加。如c=a+b。
改造上述程序,使其能够表示任意行列的矩阵,并能执行c=a+b。用运算符重载写程序,我是新手不会写,请高手帮下忙...
改造上述程序,使其能够表示任意行列的矩阵,并能执行c=a+b。用运算符重载写程序,我是新手不会写,请高手帮下忙
展开
展开全部
#include<iostream.h>
//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];
}
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;
cin>>m1;
cout<<"输入第二个数组:"<<endl;
cin>>m2;
m = m1 + m2;
cout<<"两数组相加后结果:"<<endl;
cout<<m;
}
看来c++的实验都差不多。我们的是3行3列。道理一样。看看过程修改数值就行。不过还是要自己想想做。我也是参考别人的再自己修改。加油~
//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];
}
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;
cin>>m1;
cout<<"输入第二个数组:"<<endl;
cin>>m2;
m = m1 + m2;
cout<<"两数组相加后结果:"<<endl;
cout<<m;
}
看来c++的实验都差不多。我们的是3行3列。道理一样。看看过程修改数值就行。不过还是要自己想想做。我也是参考别人的再自己修改。加油~
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询