习题 10.4 有两个矩阵a和b,均为2行3列。求两个矩阵之和。重载运算符“+”,使之能用于矩阵相加。如:c=a+b。
代码:
#include<iostream>
using namespace std;
class Arr
{
public:
void input();
void display();
friend Arr (operator +)(Arr, Arr);
private:
double arr[2][3];
};
void Arr::input() //定义输入数据函数
{
cout << "输入矩阵的值:" << endl;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
cin >> arr[i][j];
}
}
}
void Arr::display()
{
cout << endl;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
cout << arr[i][j] << " ";
}
cout << endl;
}
}
int main()
{
Arr a1, a2, a3;
a1.input();
a2.input();
a3 = a1 + a2;
a3.display();
return 0;
}
Arr operator +(Arr a1,Arr a2)
{
Arr a;
int i, j ;
for (i = 0; i != 2; ++i)
{
for (j = 0; j != 3; ++j)
{
a.arr[i][j] = a1.arr[i][j] + a2.arr[i][j];
}
}
return a;
}