YTU 2442: C++習題 矩陣求和--重載運算子__C++

來源:互聯網
上載者:User
2442: C++習題 矩陣求和--重載運算子 時間限制: 1 Sec   記憶體限制: 128 MB
提交: 1457   解決: 565
題目描述

有兩個矩陣a和b,均為2行3列。求兩個矩陣之和。重載運算子“+”,使之能用於矩陣相加(如c=a+b)。
重載流插入運算子“<<”和流提取運算子“>>”,使之能用於該矩陣的輸入和輸出。 輸入

兩個2行3列矩陣 輸出

矩陣之和 範例輸入

1 2 34 5 67 8 91 2 3
範例輸出
8 10 125 7 9
提示

前置代碼及類型定義已給定如下,提交時不需要包含,會自動添加到程式前部



/* C++代碼 */

#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];

};





主函數已給定如下,提交時不需要包含,會自動添加到程式尾部



/* C++代碼 */



int main()

{

    Matrix a,b,c;

    cin>>a;

    cin>>b;

    c=a+b;

    cout<<c<<endl;

    return 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];};istream & operator>>(istream &  input,Matrix & m){    int i,j;    for(i=0; i<2; i++)        for(j=0; j<3; j++)            input>>m.mat[i][j];    return input;}Matrix::Matrix(){    int i,j;    for(i=0; i<2; i++)        for(j=0; j<3; j++)            mat[i][j]=0;}ostream& operator <<(ostream &output,Matrix &m){    int i,j;    for(i=0; i<2; ++i)    {        for( j=0; j<2; ++j)        {            output<<m.mat[i][j]<<" ";        }        output<<m.mat[i][j]<<endl;    }    return output;}Matrix operator+(Matrix &m1,Matrix &m2){    Matrix m;    for(int i=0; i<2; ++i)        for(int j=0; j<3; ++j)        {            m.mat[i][j]=m1.mat[i][j]+m2.mat[i][j];        }    return m;}int main(){    Matrix a,b,c;    cin>>a;    cin>>b;    c=a+b;    cout<<c<<endl;    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.