运算符重载(矩阵运算)

 

Matrix.h
#include"Matrix.h"    
#include
using namespace std;
Matrix::Matrix(int r = 0,int c = 0)
{
    row = r;
    column = c;
}
Matrix Matrix::operator+ (const Matrix &m)
{
    Matrix temp(3, 3);
    if (row != m.row || column != m.column)
        cout << "这两个矩阵不能相加" << endl;
    else
    {

    for (int i = 0; i < m.row; i++)
        for (int j = 0; j < m.column; j++)
        {
        temp.M[i][j] = M[i][j] + m.M[i][j];
        }
    }
    
    return temp;
}


Matrix Matrix::operator- (const Matrix &m)
{
    Matrix temp(3, 3);
    if (row != m.row || column != m.column)
        cout << "这两个矩阵不能相减" << endl;
    else
    {
        for (int i = 0; i < m.row; i++)
            for (int j = 0; j < m.column; j++)
            {
            temp.M[i][j] = M[i][j] - m.M[i][j];
            }
    }
    
    return temp;
}


Matrix Matrix::operator* (const Matrix &m)
{
    Matrix temp(3, 3);
    if (row != m.column || column != m.row)
        cout << "这两个矩阵不能相乘" << endl;

    else
    {
        for (int i = 0; i < m.row; i++)
            for (int j = 0; j < m.column; j++)
                temp.M[i][j] = 0;

        for (int i = 0; i < m.row; i++)
        {
            for (int j = 0; j < m.column; j++)
            {
                for (int k = 0; k < m.row; k++)
                {
                    temp.M[i][j] = temp.M[i][j] + M[i][j] * m.M[k][i];
                }
            }
        }

    }
    
    return temp;
}

void Matrix::operator +=(const Matrix &m)
{
    for (int i = 0; i < m.row; i++)
        for (int j = 0; j < m.column; j++)
            M[i][j] = M[i][j]+m.M[i][j];
}
Matrix& Matrix::operator =(const Matrix &m)
{
    for (int i = 0; i < m.row; i++)
        for (int j = 0; j < m.column; j++)
            this->M[i][j] = m.M[i][j];
    return *this;
}

int Matrix::operator ()(int r, int c)
{
    return M[r][c];
}




istream& operator >>(istream &is,Matrix &m)
{
    int(*p)[10];
    int *q;
    for (p = m.M; p < m.M + m.row; p++)
        for (q = *p; q < *p + m.column; q++)
            is >> *q;
    return is;
}
ostream& operator <<(ostream &os, Matrix &m)
{
    int i, j;
    for (i = 0; i < m.row; i++)
    {
        for (j = 0; j < m.column; j++)
        {
            os << m.M[i][j]<<"  ";
        }
        os << endl;
    }
    return os;
}
Matrix.cpp
#include"Matrix.h"    
#include
using namespace std;
int main()
{
    Matrix m1(3,3), m2(3, 3), m3(3, 3);
    cin >> m1;
    cin >> m2;

    m3 = m1;    
    cout<endl ;

    

    m3 =m1*m2;

    cout << m3 << endl;

     


    

    system("pause");
    return 0;
}
/*
1 2 3
4 5 6
7 8 9
1 2 3
4 5 6
7 8 9

*/
demo.cpp

 

转载于:https://www.cnblogs.com/da-peng/p/5003999.html

你可能感兴趣的:(运算符重载(矩阵运算))