zoukankan      html  css  js  c++  java
  • 第十五周oj刷题——Problem M: C++习题 矩阵求和--重载运算符

    Description

    有两个矩阵a和b,均为2行3列。求两个矩阵之和。重载运算符“+”,使之能用于矩阵相加(如c=a+b)。
    重载流插入运算符“<<”和流提取运算符“>>”。使之能用于该矩阵的输入和输出。

    Input

    两个2行3列矩阵

    Output

    矩阵之和

    Sample Input

    1 2 3
    4 5 6
    
    7 8 9
    1 2 3
    

    Sample Output

    8 10 12
    5 7 9
    
    /* All rights reserved.
     * 文件名:test.cpp
     * 作者:陈丹妮
     * 完毕日期:2015年 6 月 21 日
     * 版 本 号:v1.0
     */
    #include <iostream>
    using namespace std;
    class Matrix
    {
    public:
        Matrix();
        friend Matrix operator+(Matrix &,Matrix &);
        friend ostream& operator<<(ostream&,Matrix&);
        friend istream& operator>>(istream&,Matrix&);
    private:
        int mat[2][3];
    };
    Matrix::Matrix()
    {int i=0,j=0;
    for(;i<2;i++)
    for(;j<3;j++)
    mat[i][j]=0;
    }
    
    
    Matrix operator+(Matrix &m1,Matrix &m2)
    {
        Matrix m;
        int i,j;
        for(i=0; i<2; i++)
        {
            for(j=0; j<3; j++)
                m.mat[i][j]=m1.mat[i][j]+m2.mat[i][j];
        }
        return m;
    }
    ostream& operator<<(ostream&out,Matrix&m)
    {
        int i,j;
        for(i=0; i<2; i++)
              {for(j=0; j<3; j++)
                out<<m.mat[i][j]<<" ";
                cout<<endl;}
        return out;
    }
    istream& operator>>(istream&in,Matrix&m)
    {
        int i,j;
        for(i=0; i<2; i++)
            for(j=0; j<3; j++)
                in>>m.mat[i][j];
        return in;
    }
    int main()
    {
        Matrix a,b,c;
        cin>>a;
        cin>>b;
        c=a+b;
        cout<<c<<endl;
        return 0;
    }
    
    

    学习心得:继续加油,重载非常好用的,得要总结一下了!

    !!!

    
       
    
  • 相关阅读:
    简单批处理语法结构
    简单批处理常用命令
    简单批处理符号简介
    简单批处理内部命令
    jQuery操作DOM
    jQuery中的事件与动画
    jQuery选择器
    初始面向对象
    初识jQuery
    操作DOM
  • 原文地址:https://www.cnblogs.com/mfmdaoyou/p/6851524.html
Copyright © 2011-2022 走看看