习题 10.4 有两个矩阵a和b,均为2行3列。求两个矩阵之和。重载运算符“+”,使之能用于矩阵相加。如:c=a+b。

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/navicheung/article/details/82704520

C++程序设计(第三版) 谭浩强 习题10.4 个人设计

习题 10.4 有两个矩阵a和b,均为2行3列。求两个矩阵之和。重载运算符“+”,使之能用于矩阵相加。如:c=a+b。

代码块:

#include <iostream>
#include <iomanip>
using namespace std;
class Array
{
public:
    Array();
    friend Array operator+(Array a1, Array a2);
    void input();
    void display();
private:
    int arr[2][3];
};
Array::Array()
{
    int i, j;
    for (i=0; i<2; i++)
        for (j=0; j<3;j++)
            arr[i][j]=0;
}
Array operator+(Array a1, Array a2)
{
    Array a3;
    int i, j;
    for (i=0; i<2; i++)
        for (j=0; j<3; j++)
            a3.arr[i][j]=a1.arr[i][j]+a2.arr[i][j];
    return a3;
}
void Array::input()
{
    cout<<"Please enter array:";
    for (int i=0; i<2; i++)
        for (int j=0; j<3; j++)
            cin>>arr[i][j];
}
void Array::display()
{
    int i, j;
    for (i=0; i<2; cout<<endl, i++)
        for (j=0; j<3; cout<<setw(4)<<arr[i][j]<<' ', j++);
}
int main()
{
    Array a, b, c;
    a.input();
    b.input();
    c=a+b;
    c.display();
    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/navicheung/article/details/82704520