版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/navicheung/article/details/82705005
C++程序设计(第三版) 谭浩强 习题10.5 个人设计
习题 10.5 在第4题的基础上,重载流插入运算符“<<”和流提取运算符“>>”,使之能用于该矩阵的输入和输出。
代码块:
#include <iostream>
#include <iomanip>
using namespace std;
class Array
{
public:
Array();
friend Array operator+(Array a1, Array a2);
friend istream& operator>>(istream &, Array &);
friend ostream& operator<<(ostream &, Array &);
private:
int arr[2][3];
};
Array::Array()
{
int i, j;
for (i=0; i<2; i++)
for (j=0; j<3; arr[i][j++]=0);
}
Array operator+(Array a1, Array a2)
{
Array a3;
for (int i=0; i<2; i++)
for (int j=0; j<3; j++)
a3.arr[i][j]=a1.arr[i][j]+a2.arr[i][j];
return a3;
}
istream& operator>>(istream &input, Array &a)
{
int i, j;
cout<<"Please enter array: ";
for (i=0; i<2; i++)
for (j=0; j<3; j++)
input>>a.arr[i][j];
return input;
}
ostream& operator<<(ostream &output, Array &a)
{
int i, j;
for (i=0; i<2; output<<endl, i++)
for (j=0; j<3; output<<setw(4)<<a.arr[i][j], j++);
return output;
}
int main()
{
Array a, b, c;
cin>>a;
cin>>b;
c=a+b;
cout<<c;
system("pause");
return 0;
}