C++定义一个N*M的矩阵类

#include<iostream>  
using namespace std;  
  
template<class T>  
class Matrix{  
public:  
    Matrix(int N, int M); //构造函数  
    Matrix(const Matrix &mat);  //拷贝构造函数  
    ~Matrix();  //析构函数  
    void SetElement();  
    void Display();  
  
private:  
    int _rows;  
    int _cols;  
    T** _p;  
};  
  
template<class T>  
Matrix< T >::Matrix(int N, int M){  
    _rows = N;  
    _cols = M;  
    _p = new T*[_rows];  
    for (int i = 0; i < _rows; i++){  
        _p[i] = new T[_cols];  
    }  
}  
  
template<class T>  
Matrix< T >::Matrix(const Matrix &mat){  
    _rows = mat._rows;  
    _cols = mat._cols;  
    _p = new T*[_rows];  
    for (int i = 0; i < _rows; i++){  
        _p[i] = new T[_cols];  
        for (int j = 0; j < _cols; j++){  
            _p[i][j] = mat._p[i][j];  
        }  
    }  
}  
  
template<class T>  
Matrix< T >::~Matrix(){  
    for (int i = 0; i <_rows ; i++){  
        delete[]_p[i];  
    }  
    delete[]_p;  
    //cout << "析构函数被调用" << endl;  
}  
  
template<class T>  
void Matrix< T >::SetElement(){  
    cout << "请输入矩阵的元素,共" << _rows*_cols << "个:" << endl;  
    for (int i = 0; i < _rows; i++){  
        for (int j = 0; j < _cols; j++){  
            cin >> _p[i][j];  
        }  
    }  
}  
  
template<class T>  
void Matrix< T >::Display(){  
    for (int i = 0; i < _rows; i++){  
        for (int j = 0; j < _cols; j++){  
            if (j)cout << "  ";  
            cout<<_p[i][j];  
        }  
        cout << endl;  
    }  
}  
int main()  
{  
    int n, m;  
    cout << "请输入行数: ";  
    cin >> n;  
    cout << "请输入列数: ";  
    cin >> m;  
    Matrix<double> mat(n, m);  
    mat.SetElement();  
    mat.Display();  
    cout << "拷贝构造得到的矩阵:" << endl;  
    Matrix<double> mat2(mat);  
    mat2.Display();  
    return 0;  
}

请输入行数: 3

请输入列数: 4

请输入矩阵的元素,共12个:

1 2 3 4 5 6 7 8 9.0 10 11 -12

1  2  3  4

5  6  7  8

9  10  11  -12

拷贝构造得到的矩阵:

1  2  3  4

5  6  7  8

9  10  11  -12

请按任意键继续. . .

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值