我想要输入一个二维数组,这是Matrix.h
#include <iostream>
using namespace std;
class Matrix
//定义Matrix类
{
public:
Matrix(){
this->mat = new int*[100];
int i = 0;
for(i = 0;i < 100;i++){
this->mat[i] = new int[100];
}
this->row = 0;
this->col = 0;
} //默认构造函数
~Matrix(){
int i = 0;
for(i = 0;i < 100;i++){
delete []this->mat[i];
}
delete []this->mat;
} //析构函数
Matrix(const Matrix &ptr){
this->mat = new int*[100];
int i = 0;
for(i = 0;i < 100;i++){
this->mat[i] = new int[100];
}
int i1, i2;
for(i1 = 0;i1 < row;i1++){
for(i2 = 0;i2 < col;i2++){
this->mat[i1][i2] = ptr.mat[i1][i2];
}
}
this->row = ptr.row;
this->col = ptr.col;
} //拷贝构造函数
Matrix(int row, int col){
this->mat = new int*[100];
int i, i1, i2;
for(i = 0;i < 100;i++){
this->mat[i] = new int[100];
}
for(i1 = 0;i1 < row;i1++){
for(i2 = 0;i2 < col;i2++){
cin >> this->mat[i1][i2];
}
}
this->row = row;
this->col = col;
} //含参数构造函数
Matrix operator+(const Matrix &ptr)const{
Matrix kp = Matrix();
int i1, i2;
for(i1 = 0;i1 < this->row;i1++){
for(i2 = 0;i2 < this->col;i2++){
kp.mat[i1][i2] = this->mat[i1][i2] + ptr.mat[i1][i2];
}
}
return kp;
} //重载运算符“+”
Matrix& operator=(const Matrix &ptr){
Matrix gl = Matrix();
int i1, i2;
for(i1 = 0;i1 < ptr.row;i1++){
for(i2 = 0;i2 < ptr.col;i2++){
this->mat[i1][i2] = ptr.mat[i1][i2];
}
}
return *this;
} //重载运算符“=”
Matrix transpose()const{
Matrix nf = Matrix();
int i1, i2;
for(i1 = 0;i1 < this->row;i1++){
for(i2 = 0;i2 < this->col;i2++){
nf.mat[i1][i2] = this->mat[i1][i2];
}
}
nf.row = this->row;
nf.col = this->col;
return nf;
} //矩阵的转置
void display()const{
int i1, i2;
for(i1 = 0;i1 < row;i1++){
for(i2 = 0;i2 < col;i2++){
cout << mat[i1][i2] << " ";
}
cout << endl;
}
} //输出数据函数
private:
int row; //矩阵的行
int col; //矩阵的列
int** mat; //用于储存矩阵
};
这是Matrix.cpp
#include <iostream>
#include"Matrix.h"
using namespace std;
int main() {
int row, col;
cout << "input the row and the col for Matrix a, b" << endl;
cin >> row >> col;
Matrix a(row, col), b(row, col), c(a), d;
cout << endl << "Matrix a:" << endl;
a.display();
cout << endl << "Matrix b:" << endl;
b.display();
c = a + b;//用重载运算符“+”实现两个矩阵相加
cout << endl << "Matrix c = Matrix a + Matrix b :" << endl;
c.display();
cout << endl << "Matrix a transpose to Matrix d:" << endl;
d = a.transpose();
d.display();
return 0;
}
要求的输入输出是这样的:
输入:
2 3
1 2 3
1 2 3
1 2 3
1 2 3
输出:
input the row and the col for Matrix a, b
Matrix a:
1 2 3
1 2 3
Matrix b:
1 2 3
1 2 3
Matrix c = Matrix a + Matrix b :
2 4 6
2 4 6
Matrix a transpose to Matrix d:
1 1
2 2
3 3
但是实际输出是这样的:
input the row and the col for Matrix a, b
Matrix a:
1 2 3
1 2 3
Matrix b:
1 2 3
1 2 3
Matrix c = Matrix a + Matrix b :
2 4 6
2 4 6
Matrix a transpose to Matrix d:
1 1
2 2
3 3
请问错在哪?