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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_30432997/article/details/85002615
#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

请按任意键继续. . .

猜你喜欢

转载自blog.csdn.net/qq_30432997/article/details/85002615