矩阵

题目:编写程序实现实数矩阵类。

要求:实现矩阵的加法、减法、乘法

分析:运用重载运算符的方法,对<<、>>+、-、*进行重载

//Matrix.h
#ifndef MATRIX_H_INCLUDED
#define MATRIX_H_INCLUDED

#include<iostream>

class Matrix
{
    friend std::istream& operator>>(std::istream& in,Matrix &c);
    friend std::ostream& operator<<(std::ostream& out,const Matrix &c);
    friend Matrix operator+(const Matrix &c1, const Matrix &c2);
    friend Matrix operator-(const Matrix &c1, const Matrix &c2);
    friend Matrix operator*(const Matrix &c1, const Matrix &c2);
    int *elem;
    int row;
    int col;
public:
    Matrix(int r =0,int c=0):row(r),col(c)
    {
        elem = new int[r*c];
    }
    ~Matrix();

};


#endif // MATRIX_H_INCLUDED

//Matrix.cpp
#include<iostream>
#include "Matrix.h"
#include<string.h>

Matrix::~Matrix()
{
    delete[]elem;
}
std::istream& operator>>(std::istream& in, Matrix &c)
{
    for(int i=0; i<c.row; i++)
    {
        for(int j=0;j<c.col;j++)
        {
            in>>c.elem[i*c.col + j];
        }
    }
    return in;
}

std::ostream& operator<<(std::ostream& out,const Matrix &c)
{
    for(int i=0;i<c.row;i++)
    {
        for(int j=0;j<c.col;j++)
        {
            out << c.elem[i*c.col + j] << ' ';
        }
        out<<std::endl;
    }
    out<<std::endl;
    return out;
}

Matrix operator+(const Matrix &c1, const Matrix &c2)
{
    Matrix tmp(c2.row, c2.col);
    for(int i=0;i<c1.row;i++)
    {
        for(int j=0;j<c1.col;j++)
        {
            tmp.elem[i*c2.col + j] = c1.elem[i*c2.col + j] + c2.elem[i*c2.col + j];
        }
    }
    return tmp;
}

Matrix operator-(const Matrix &c1, const Matrix &c2)
{
    Matrix tmp(c2.row, c2.col);
    for(int i=0;i<c1.row;i++)
    {
        for(int j=0;j<c1.col;j++)
        {
            tmp.elem[i*c2.col + j] = c1.elem[i*c2.col + j] - c2.elem[i*c2.col + j];
        }
    }
    return tmp;
}

Matrix operator*(const Matrix &c1, const Matrix &c2)
{
    Matrix tmp(c1.row, c2.col);
    int x=0;
    for(int i=0;i<c1.row;i++)
    {
        for(int j=0;j<c2.col;j++)
        {
                for(int n=0;n<c2.row;n++)
                {
                    x += c1.elem[i*c1.col+n] * c2.elem[n*c2.col+j];
                }
                tmp.elem[i*c2.col+j] = x;
                x=0;
        }
    }
    return tmp;
}

//main.cpp
#include<iostream>
#include"Matrix.h"

int main()
{
    Matrix c1(3,3);
    Matrix c2(3,1);
    std::cin>>c1;
    std::cin>>c2;
    //std::cout<<c1+c2;
    //std::cout<<c1-c2;
    std::cout<<c1*c2;
    //std::cout<<c1/c2;

}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值