1.题目:
Problem Description
设计一个矩阵类Data,包括矩阵的行、列、矩阵数据等私有数据成员。要求实现两个矩阵的加。
Input
输入数据有多组,每组输入数据有三行,第一行两个整数,分别代表矩阵的行数m和列数n;第二行有m*n个整数,是第一个矩阵的数据;第三行也有m*n个整数,是第二个矩阵的数据。
Output
对于每组输入数据,输出两个矩阵的和。
Sample Input
3 3
1 1 1 2 2 2 3 3 3
1 1 1 1 1 1 1 1 1
2 3
1 2 3 4 5 6
1 1 1 1 1 1
Sample Output
2 2 2
3 3 3
4 4 4
2 3 4
5 6 7
2.下面这个代码没有真正达到目的:
#include <iostream> using namespace std; #define N 500 class Data{ private: int row, col, *a; public: Data(); Data(int* b, int& l, int& r); Data operator+(Data&); void show(); }; Data::Data() { row = 0; col = 0; int* b = new int[N]; a = b; } Data::Data(int* b, int& l, int& r) { row = l; col = r; a = b; } Data Data::operator+(Data& c) { Data sum; sum.row = c.row; sum.col = c.col; for (int i = 0; i < row * col; i++) sum.a[i] = a[i] + c.a[i]; return sum; } void Data::show() { int i, j, k = 0; for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { if (j == 0) cout << a[k++]; else cout << ' ' << a[k++]; } cout << endl; } } int main() { int m, n, i, j, a[N], b[N]; while (cin >> m >> n) { for (i = 0; i < m * n; i++) cin >> a[i]; for (j = 0; j < m * n; j++) cin >> b[j]; Data x(a, m, n), y(b, m, n), z; z = x + y; z.show(); } return 0; }
看看现在这段代码:
#include <iostream> //#include <stdio.h> using namespace std; class Matrix { const int row, col; int* a; public: Matrix(int r, int c); Matrix(Matrix& m); ~Matrix(); Matrix& operator=(Matrix& m); Matrix operator+(Matrix& m); friend istream& operator>>(istream& in, Matrix& m); friend ostream& operator<<(ostream& out, Matrix& m); }; Matrix::Matrix(int r, int c): col(c), row(r) { int i; a = new int[r * c]; for (i = 0; i < r * c; i++) a[i] = 0; } Matrix::Matrix(Matrix& m): col(m.col), row(m.row) { int i; a = new int[col * row]; for (i = 0; i < col * row; i++) a[i] = m.a[i]; } Matrix::~Matrix() { delete []a; } Matrix& Matrix::operator=(Matrix& m) { int i; if (m.row == row && m.col == col) for (i = 0; i < row * col; i++) a[i] = m.a[i]; return *this; } Matrix Matrix::operator+(Matrix& m) { Matrix b(m.row, m.col); int i; for (i = 0; i < row * col; i++) b.a[i] = m.a[i] + a[i]; return b; } istream& operator>>(istream& in, Matrix& m) { int i; for (i = 0; i < m.row * m.col; i++) { cin >> m.a[i]; } return in; } ostream& operator<<(ostream& out, Matrix& m) { int i, j; for (i = 0; i < m.row; i++) { for (j = 0; j < m.col; j++) { if (j == 0) cout << m.a[i * m.col + j]; else cout << " " << m.a[i * m.col + j]; } cout << endl; } return out; } int main() { // freopen("1.txt", "r", stdin); int a, b; while (cin >> a >> b) { Matrix x(a, b); cin >> x; Matrix y(a, b); cin >> y; cout << x + y; } return 0; }