有两个矩阵a和b,均为2行3列。求两个矩阵之和。重载运算符"+",使之能用于矩阵相加,如:c = a + b.
#include <iostream> using namespace std;
class Matrix { public: void input(); //用于输入数据
void display(); //显示数据函数
friend Matrix operator +(Matrix m1,Matrix m2); //定义重载函数
private: int data[2][3] ; //定义矩阵使用的数组,私有成员
};
void Matrix::input() { int (*p)[3]; //定义指向一维数组的指针变量
int *q; //定义int 类型指针
for(p = data;p < data + 2;p++) { for (q = *p; q < *p + 3;q++) { cin >> *q; } } }
void Matrix::display() { int (*p)[3]; int *q; for(p = data;p < data + 2;p++) { for (q = *p; q < *p + 3;q++) { cout << *q << " "; } cout << endl; } }
Matrix operator +(Matrix m1,Matrix m2) { Matrix result; int (*p)[3]; int *q; int (*pm1)[3],(*pm2)[3]; int *pm11,*pm12; for(pm1 = m1.data,pm2 = m2.data,p = result.data;p < result.data + 2;p++,pm1++,pm2++) { for (pm11 = *pm1,pm12 = *pm2,q = *p; q < *p + 3;q++,pm11++,pm12++) { *q = *pm11 + *pm12; } } return result; }
int main() { Matrix m1,m2,m3; m1.input(); m2.input(); m3 = m1 + m2; m3.display(); system("pause"); return 0; }
|
阅读(2804) | 评论(0) | 转发(0) |