定义一个Matrix类,实现矩阵的加法和乘法

软件设计 2017-03-31

#include<iostream>
using namespace std;

class Matrix
{
    int row;//矩阵的行
    int col;//矩阵的列
    int **a;//保存二维数组的元素
public:
    Matrix();//默认构造函数
    Matrix(int r, int c);
    Matrix(const Matrix &is);//拷贝构造函数
    void Madd(const Matrix &is);//矩阵加
    Matrix Mmul(const Matrix &is);//矩阵乘
    void display();//显示矩阵元素
};

Matrix::Matrix(int r, int c)
{
    row = r;
    col = c;
    a = (int **)malloc(sizeof(int*)*row);
    for (int r = 0; r < row; r++)
    {
        *(a + r) = (int*)malloc(sizeof(int)*col);
    }
    printf("请输入数:\n");
    for (int i = 0; i < row; i++)
        for (int j = 0; j < col; j++)
            cin >> a[i][j];
}

Matrix::Matrix(const Matrix & is)
{//拷贝构造函数
    row = is.row;
    col = is.col;
    a = new int*[row];
    for (int i = 0; i < row; i++)
    {
        a[i] = new int[col];
    }
    a = is.a;
}

void Matrix::Madd(const Matrix & is)
{
    if (row != is.row || col != is.col)//判断两矩阵是否符合相加条件
    {
        cout << "相加的矩阵必须行和列一致";
    }
    else
    {
        for (int i = 0; i < row; i++)
        {
            for (int j = 0; j < col; j++)
            {
                a[i][j] += is.a[i][j];
            }
        }
    }
}

Matrix Matrix::Mmul(const Matrix & is)
{
    Matrix M3(this->row, is.col);
    if (this->col != is.row)//判断是否符合相乘条件
    {
        cout << "不符合两矩阵相乘的条件";
    }
    else
    {
        for (int i = 0; i < M3.row; i++)
        {
            for (int j = 0; j < M3.col; j++)
            {
                M3.a[i][j] = 0;
                for (int n = 0; n < is.row; n++)
                {
                    M3.a[i][j] += this->a[i][n] * is.a[n][j];
                }
            }
        }
    }
    return M3;
}

void Matrix::display()
{//输出矩阵
    for (int i = 0; i < row; i++)
    {
        for (int j = 0; j < col; j++)
        {
            cout << a[i][j] << " ";
        }
        cout << endl;
    }
    cout << endl;
}

int main()
{
    Matrix m1(3, 3);
    m1.display();
    Matrix m2(3, 3);
    m2.display();
    Matrix m3(3, 2);
    m3.display();
    cout << "m1+m2=" << endl;
    m1.Madd(m2);
    m1.display();
    Matrix m4(m1.Mmul(m3));
    cout << "m1*m3=" << endl;
    m4.display();
    system("pause");
    return 0;
}

运行结果:

相关推荐