《第九周实验报告四》
2012-04-18 17:59
232 查看
/*
* 程序的版权和版本声明部分
* Copyright (c) 2011, 烟台大学计算机学院学生
* All rights reserved.
* 文件名称:* 作 者: 张斌
* 完成日期: 2012年 4 月 18 日
* 版 本 号: 9-2-1
* 对任务及求解方法的描述部分
* 代码实现
#include <iostream> using namespace std; class Douary { public: Douary(int m, int n);//构造函数:用于建立动态数组存放m行n列的二维数组(矩阵)元素,并将该数组元素初始化为 Douary(const Douary &d); ~Douary(){delete [] Array;} //析构函数:用于释放动态数组所占用的存储空间。 friend istream & operator >> (istream &input, Douary &d);//重载运算符“>>”输入二维数组,其中d为Dousry类对象; friend ostream & operator << (ostream &output, Douary &d);//重载运算符“<<”以m行n列矩阵的形式输出二维数组, //其中d为Douary类对象。 friend Douary operator + (const Douary &d1, const Douary &d2);//两个矩阵相加,规则:对应位置上的元素相加 friend Douary operator - (const Douary &d1, const Douary &d2);//两个矩阵相减,规则:对应位置上的元素相减 bool operator == (const Douary &d);//判断两个矩阵是否相等,即对应位置上的所有元素是否相等 private: int * Array; //Array 为动态数组指针。 int row; //row 为二维数组的行数。 int col; //col 为二维数组的列数。 }; Douary::Douary(int m, int n) { row = m, col = n; Array = new int [row*col]; for (int i = 0; i < row*col; i++) Array[i] = 0; } Douary::Douary(const Douary &d) { col = d.col, row = d.row; Array = new int[row*col]; for (int i = 0; i < row*col; i++) Array[i] = d.Array[i]; } istream & operator >> (istream &input, Douary &d) { cout << "请输入元素(" << d.row << "行" << d.col <<"列):" << endl; for (int i = 0; i < d.col*d.row; i++) { input >> d.Array[i]; } return input; } ostream & operator << (ostream &output, Douary &d) { for (int i = 0; i < d.col*d.row; i++) { if (i % d.col == 0) cout << endl; output << d.Array[i] <<'\t'; } cout << endl; return output; } Douary operator + (const Douary &d1, const Douary &d2) { Douary D(d1); for (int i = 0; i < d1.col*d1.row; i++) D.Array[i] = d1.Array[i] + d2.Array[i]; return D; } Douary operator - (const Douary &d1, const Douary &d2) { Douary D(d1); for (int i = 0; i < d1.col*d1.row; i++) D.Array[i] = d1.Array[i] - d2.Array[i]; return D; } bool Douary::operator == (const Douary &d) { if (this->col == d.col && this->row == d.row) { for (int i = 0; i < d.col*d.row; i++) if (*(this->Array+i) != *(d.Array+i)) return false; } else return false; return true; } int main() { Douary d1(2, 3), d2(2, 3); cout << "输入d1:" << endl; cin >> d1; cout << "输入d2:" << endl; cin >> d2; cout << "d1=" ; cout << d1; cout << "d2="; cout << d2; cout << "d1+d2="; cout << (d1+d2); cout << "d1-d2="; cout << (d1-d2); cout << "d1" << ((d1==d2)? "==":"!=") << "d2" << endl; system("pause"); return 0; }
运行结果: