閱讀49 返回首頁    go 阿裏雲 go 技術社區[雲棲]


第五章5.15作業題

/*
*編一個程序,用成員函數重載運算符"+"和"-",將
*兩個二維數組相加和相減,要求第一個二維數組的
*值由構造函數設置,另一個二維數組的值由鍵盤輸入。
*/

#ifndef ARRAY2D_H
#define ARRAY2D_H

class Array2D
{
    public:
        Array2D();
        Array2D(int arr[][20], int r, int c);
        virtual ~Array2D(){};

        Array2D operator+(const Array2D & src);
        Array2D operator-(const Array2D & src);
        friend ostream & operator<<(ostream &, const Array2D & src);
    private:
        int array[20][20];
        int row; //行
        int col; //列
};

#endif //ARRAY2D_H


#include <iostream>
using namespace std;

#include "Array2D.h"

Array2D::Array2D()
{
    row = 20;
    col = 20;
    for (int i = 0; i < row; i++)
    {
        for (int j = 0; j < col; j++)
        {
            array[i][j] = 0;
        }
    }

}

Array2D::Array2D(int arr[][20], int r, int c)
{
    for (int i = 0; i < r; i++)
    {
        for (int j = 0; j < c; j++)
        {
            array[i][j] = arr[i][j];
        }
    }
    row = r;
    col = c;
}

Array2D Array2D::operator+(const Array2D & src)
{
    Array2D tmp;

    for (int i = 0; i < src.row; i++)
    {
        for (int j = 0; j < src.col; j++)
        {
           tmp.array[i][j] = array[i][j] + src.array[i][j];
        }
    }
    tmp.row = row;
    tmp.col = col;

    return tmp;
}


Array2D Array2D::operator-(const Array2D & src)
{
    Array2D tmp;

    for (int i = 0; i < row; i++)
    {
        for (int j = 0; j < col; j++)
        {
            tmp.array[i][j] = array[i][j] - src.array[i][j];
        }
    }
    tmp.row = row;
    tmp.col = col;

    return tmp;
}

ostream & operator<<(ostream & out, const Array2D & src)
{
    for (int i = 0; i < src.row; i++)
    {
        for (int j = 0; j < src.col; j++)
        {
            cout << src.array[i][j] << " ";
        }
        cout << endl;
    }
    return out;
}


#include <iostream>
using namespace std;

#include <conio.h>
#include "Array2D.h"

int main()
{
    int arr[2][20] = {{1, 1}, {2, 2}};
    Array2D arr1(arr, 2, 2);

    int tmp[2][20] = {{0}};
    cout << "輸入2*2矩陣:" << endl;
    for (int i = 0; i < 2; i++)
    {
        for (int j = 0; j < 2; j++)
        {
            cin >> tmp[i][j];
        }
    }

    Array2D arr2(tmp, 2, 2);

    cout << "arr1: \n" << arr1 << endl;
    cout << "arr2: \n" << arr2 << endl;
    cout << "arr1+arr2: \n" << arr1 + arr2 << endl;
    cout << "arr1-arr2: \n" << arr1 - arr2 << endl;

    getch();
    return 0;
}
/*
運行結果:

輸入2*2矩陣:
2 3
3 4
arr1:
1 1
2 2

arr2:
2 3
3 4

arr1+arr2:
3 4
5 6

arr1-arr2:
-1 -2
-1 -2
*/

最後更新:2017-04-02 15:15:24

  上一篇:go Android把view的畫麵轉換為bitmap
  下一篇:go 失控的騰訊開始自救