今天的初衷是使用C++完成一个矩阵类的创建,并且实现基本运算。
而这里我打算使用动态分配空间,因此就有了这个记录
这里我使用的是 dev C++:
class Matrix{
friend Matrix operator+(const Matrix &a,const Matrix &b);
friend Matrix operator-(const Matrix &a,const Matrix &b);
private:
int row;
int column;
int **space; //这里尝试实现动态的二维数组
void assign();
public:
Matrix(int r,int c){
row=r;
column=c;
space=new int*[row]; //可以看见这里是创建了第一层的“行”
for(int i=0;i<row;i++){
space[i]=new int[column]; //这里使用循环创建第二层列
}
assign();
}
~Matrix(){
delete []*space; //这里析构可能有争议
delete []space; //我是先后删除创建层数的
}
Matrix operator*(const Matrix &b);
void display(){
for(int i=0;i<row;i++){
cout<<"|";
for(int j=0;j<column;j++){
cout<<space[i][j]<<" ";
}
cout<<"|"<<endl;
}
}
};
void Matrix::assign(){
int num;
for(int i=0;i<row;i++){
for(int j=0;j<column;j++){
cin>>num;
space[i][j]=num;
}
}
}
测试结果就是这样的: