第五章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
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值