问题描述
我正在使用c ++进行运算符重载,在此程序中,我必须在运行时从用户处获取矩阵大小和值,并对两个对象执行运算符重载(减法),并为其分配两个第三个对象,并在其中显示矩阵第三个对象,代码在下面
#include<iostream>
using std::cout;
using std::cin;
using std::endl;
class matrix{
int **matrixList;
int row;
int col;
public:
explicit matrix(){};
matrix(int**,int,int);
matrix operator-(matrix);
void getValues();
void displayMatrix();
};
matrix::matrix(int** matrixList,int row,int col){
this->matrixList=matrixList;
this->row=row;
this->col=col;
}
void matrix::getValues(){
for(int i=0;i<row;i++){
cout<<"\n enter value in row "<<i+1<<"\n";
for(int j=0;j<col;j++)
cin>>matrixList[i][j];
}
}
matrix matrix::operator-(matrix obj){
matrix tmpObj(matrixList,row,col);
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
tmpObj.matrixList[i][j]=this->matrixList[i][j]-obj.matrixList[i][j];
}
}
return tmpObj;
}
void matrix::displayMatrix(){
for(int i=0; i<row; i++){
for(int j=0;j<col; j++){
cout<<" "<<matrixList[i][j]<<" ";
}
cout<<endl;
}
}
int main(){
int **matrixPtr;
cout<<"enter no of rows : ";
int row;
cin>>row;
cout<<"enter no of columns : ";
int col;
cin>>col;
matrixPtr = new int *[row];
for(int i=0;i<row;i++){
matrixPtr[i] = new int[col];
}
matrix obj1(matrixPtr,col);
obj1.getValues();
matrix obj2(matrixPtr,col);
obj2.getValues();
matrix obj3(matrixPtr,col);
obj3=obj1-obj2;
obj3.displayMatrix();
for(int j=0;j<row;j++){
delete[] matrixPtr[j];
}
delete matrixPtr;
}
如果我在上面的代码中将行和列的大小设置为4,则会给出这样的输出
0 0
0 0
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)