/*
*编一个程序,用成员函数重载运算符"+"和"-",将
*两个二维数组相加和相减,要求第一个二维数组的
*值由构造函数设置,另一个二维数组的值由键盘输入。
*/
#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
*/
第五章5.15作业题
最新推荐文章于 2024-04-01 00:38:17 发布