矩阵求和--重载运算符

Problem D: C++习题 矩阵求和--重载运算符

[ Submit][ Status][ Web Board]

Description

有两个矩阵a和b,均为2行3列。求两个矩阵之和。重载运算符“+”,使之能用于矩阵相加(如c=a+b)。
重载流插入运算符“<<”和流提取运算符“>>”,使之能用于该矩阵的输入和输出。

Input

两个2行3列矩阵

Output

矩阵之和

Sample Input

1 2 3
4 5 6

7 8 9
1 2 3

Sample Output

8 10 1
25 7 9

HINT


#include <iostream>
using namespace std;
class Matrix
{
public:
    Matrix();
    friend Matrix operator+(Matrix &,Matrix &);
    friend ostream& operator<<(ostream&,Matrix&);
    friend istream& operator>>(istream&,Matrix&);
private:
    int mat[2][3];
};
Matrix::Matrix()
{
    for(int i=0;i<2;i++)
        for(int j=0;j<3;j++)
        {
            mat[i][j]=0;
        }
}
Matrix operator+(Matrix &a,Matrix &b)
{
    Matrix c;
    for(int i=0;i<2;i++)
        for(int j=0;j<3;j++)
        {c.mat[i][j]=a.mat[i][j]+b.mat[i][j];}
        return c;
}
istream& operator>>(istream &in,Matrix &m)
{
    for(int i=0;i<2;i++)
        for(int j=0;j<3;j++)
        {in>>m.mat[i][j];
        }
        return in;
}
ostream& operator<<(ostream &out,Matrix &m)
{
    for(int i=0;i<2;i++)
    {   for(int j=0;j<3;j++)
        {
            if(j==2)
                out<<m.mat[i][j];
            else
                out<<m.mat[i][j]<<" ";
        }
        out<<endl;
    }
        return out;
}
int main()
{
    Matrix a,b,c;
    cin>>a;
    cin>>b;
    c=a+b;
    cout<<c<<endl;
    return 0;
}


  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在C++中,我们可以使用运算符重载(operator overloading)技术来定义矩阵相乘的运算符。运算符重载是指对C++中已有的运算符进行重新定义,使其能够适用于自定义的数据类型。 我们可以通过定义一个矩阵类,并在其中重载乘法运算符(*)来实现矩阵相乘操作。在重载运算符时需要注意参数类型和返回值类型的定义。以下是一个简单的矩阵类的示例: ``` class Matrix { private: int row, col; int **data; public: Matrix(int r, int c) : row(r), col(c) { data = new int*[row]; for(int i = 0; i < row; i++) data[i] = new int[col]; } Matrix(const Matrix& m) : row(m.row), col(m.col) { data = new int*[row]; for(int i = 0; i < row; i++) data[i] = new int[col]; for(int i = 0; i < row; i++) for(int j = 0; j < col; j++) data[i][j] = m.data[i][j]; } ~Matrix() { for(int i = 0; i < row; i++) delete[] data[i]; delete[] data; } Matrix operator*(const Matrix& m) const { Matrix result(row, m.col); for(int i = 0; i < row; i++) for(int j = 0; j < m.col; j++) { result.data[i][j] = 0; for(int k = 0; k < col; k++) result.data[i][j] += data[i][k] * m.data[k][j]; } return result; } }; ``` 在上述代码中,我们定义了一个Matrix类,其中包含了矩阵的行数、列数以及数据。在类中,我们重载了乘法运算符(*),使其能够实现矩阵相乘的操作。在重载运算符时,我们需要使用const关键字来确保不会修改原对象,同时返回一个新的矩阵对象。 使用该类进行矩阵相乘操作时,只需使用乘法运算符即可,例如: ``` Matrix A(2, 3); Matrix B(3, 4); // 初始化矩阵A、B Matrix C = A * B; // 矩阵相乘操作 ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值