C++矩阵求和(重载运算符)

【问题描述】有两个矩阵a和b,均为2行3列。求两个矩阵之和。重载流插入运算符“<<”和流提取运算符“>>”,使之能用该矩阵的输入和输出。
【输入形式】input value of matrix:11 22 33 44 55 66

                    input value of matrix:12 13 14 15 16 17
【输出形式】Matirx a:

                    11 22 33

                    44 55 66

                   Matrix b:

                   12 13 14

                   15 16 17

                  Matrix c=Matrix a+Matrix b

                  23 35 47

                  59 71 83

//矩阵求和(2) 
#include <iostream>
#include <iomanip>
using namespace std;
class Array
{
public:
    Array();
    friend Array operator+(Array a1,Array a2);//破坏封装性 
    friend istream & operator >>(istream &input,Array &c1);
    friend ostream & operator <<(ostream &output,Array &c1);
private:
    int arr[2][3];
};
Array::Array()//初始化矩阵为零矩阵 
{
    int i, j;
    for (i=0; i<2; i++)
        for (j=0; j<3;j++)
            arr[i][j]=0;
}
Array operator+(Array a1, Array a2)//重载运算符+
{
    Array a3;
    int i, j;
    for (i=0; i<2; i++)
        for (j=0; j<3; j++)
            a3.arr[i][j]=a1.arr[i][j]+a2.arr[i][j];
    return a3;
}
istream & operator >>(istream &input,Array &c1)//重载运算符>>
{     
    int i,j;  
    for(i=0;i<2;i++)  
        for(j=0;j<3;j++)  
            input>>c1.arr[i][j];
	return input;
}
ostream & operator <<(ostream &output,Array &c1)//重载运算符<<
{      
    output<<c1.arr[0][0]<<" "<<c1.arr[0][1]<<" "<<c1.arr[0][2]<<endl;
	output<<c1.arr[1][0]<<" "<<c1.arr[1][1]<<" "<<c1.arr[1][2]<<endl;
	return output;
} 
int main()
{
    Array a,b,c;
    cout<<"input value of matrix:"<<endl;
    cout<<"input value of matrix:"<<endl;
    cout<<"Matrix a:"<<endl;
    cin>>a;
    cout<<a;
    cout<<"Matrix b:"<<endl;
    cin>>b;
    cout<<b;
    c=a+b;
    cout<<"Matrix c=Matrix a+Matrix b:"<<endl;
    cout<<c;
    cout<<endl;
    return 0;
}

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值