C++数据与结构第二次作业
潘隆武 21425202 机械工程
题目:定义一个N*M的矩阵类,要求:1)用指针;2)用构造函数和析构函数;3)用拷贝构造函数。
#include
#include
using namespace std;
class Matrix
{
public:
Matrix(int ,int );//构造函数
Matrix(const Matrix &);//拷贝构造函数
~Matrix();//析构函数
Creat();//矩阵赋值函数
Output();//矩阵输出函数
private:
int row;
int column;
double **pt;
};
//主函数
int main()
{
system("COLOR 0e");
int r,c;
cout<<"请输入矩阵的行数(N)和列数(M):"< cin>>r>>c; Matrix M1(r,c); M1.Creat(); cout<<"Matrix("< M1.Output(); Matrix M2(M1); cout<<"由Matrix通过拷贝构造函数创建的新矩阵Matrix'("< M2.Output(); return 0; } //创建row行column列的矩阵,并将其初始化为零阵 Matrix::Matrix(int r,int c):row(r),column(c) { if(row<1||column<1) cout<<"矩阵的行数和列数都必须大于0!"< else { pt=new double*[row]; for(int i=0;i { *(pt+i)=new double[column]; for(int j=0;j { *(*(pt+i)+j)=0.0; } } } } //拷贝构造函数,以矩阵A创建新矩阵B并以A对B进行初始化Matrix::Matrix(const Matrix &m) { row=m.row; column=m.column; pt=new double*[row]; for(int i=0;i { *(pt+i)=new double[column]; for(int j=0;j { *(*(pt+i)+j)=m.pt[i][j]; } } } //析构函数,对堆中的动态空间进行释放 Matrix::~Matrix() { if(pt!=NULL) { for(int i=0;i delete[] pt[i]; delete[] pt; } } //矩阵赋值函数,对已创建的矩阵以人工输入的方式进行赋值 Matrix::Creat() { cout<<"请输入"< for(int i=0;i { for(int j=0;j { cin>>*(*(pt+i)+j); } } cout<<"================================================================ ==============="< } //矩阵输出函数,以矩阵的形式将矩阵输出 Matrix::Output() { for(int i=0;i { for(int j=0;j { cout< } cout< } } 程序运行结果: