实现矩阵类

#ifndef GUARD_MATRIX_H
#define GUARD_MATRIX_H

#include<iostream>
#include<iomanip>
using namespace std;

template<class T=double>
class matrix{

    template<typename T>
    friend ostream& operator<<(ostream&,const matrix<T>&);
public:
    matrix(int x=0,int y=0);
    matrix(const matrix& mx);
    ~matrix(){
        free();
    }
    void setvalue(int r,int c,T x);
    matrix<T> operator+(const matrix<T>&mx) const;
    matrix<T> operator*(const matrix<T>&mx) const;
    matrix<T>& operator=(const matrix<T>&mx);
private:
    T **ptr;
    int m,n;
    void free();

};

template<class T>
matrix<T>::matrix(int x,int y){

    m=x;
    n=y;
    ptr=new T*[m];
    for(int i=0;i<m;i++)
        ptr[i]=new T[n];
}

template<class T>
matrix<T>::matrix(const matrix<T> &mx){

    m=mx.m;
    n=mx.n;
    ptr=new T*[m];
    for(int i=0;i<m;i++)
        ptr[i]=new T[n];
    for(int i=0;i<m;i++)
        for(int j=0;j<n;j++)
            ptr[i][i]=mx.ptr[i][j];
}

template<class T>
void matrix<T>::setvalue(int r, int c, T x){

    ptr[r][c]=x;
}

template<class T>
matrix<T>& matrix<T>::operator =(const matrix<T> &mx){
    free();
    m=mx.m;
    n=mx.n;
    ptr=new T*[m];
    for(int i=0;i<m,i++)
        ptr[i]=new T[n];
    for(int i=0;i<m;i++)
        for(int j=0;j<n;j++)
            ptr[i][j]=mx.ptr[i][j];
    return *this;
}

template<class T>
matrix<T> matrix<T>::operator +(const matrix<T> &mx) const{
    if(m!=mx.m||n!=mx.n)
    {
        cout<<"they can not plus"<<endl;
        return NULL;
    }
    matrix<T> temp(m,n);
    for(int i=0;i<m;i++)
        for(int j=0;j<n;j++)
            temp.ptr[i][j]=ptr[i][j]+mx.ptr[i][j];

    return temp;
}

template<class T>
void matrix<T>::free(){
    for(int i=0;i<m;i++)
        delete []ptr[i];
    delete []ptr;
    m=0;
    n=0;

}
template<class T>
matrix<T> matrix<T>::operator *(const matrix<T> &mx) const{
    if(this->n != mx.m)
    {
        cout<<"the two matrix can not multify"<<endl;
            return NULL;
    }
    matrix temp(m,mx.n);
    for(int i=0;i<m;i++)
        for(int j=0;j<mx.n;j++){
            T sum=NULL;
    for(int k=0;k<n;k++)
        sum+=ptr[i][k]*mx.ptr[k][j];
    temp.ptr[i][j]=sum;
}
        return temp;
}


template<class T>
ostream& operator<<(ostream& os, const matrix<T> &mx){
    for(int i=0;i<mx.m;i++){
        for(int j=0;j<mx.n;j++)
            os<<setw(6)<<mx.ptr[i][j];
        os<<endl;
    }
    return os;
}

#endif



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值