修正了复制构造函数(这个坑掉过好几次额…)
完善交互
1 //matrix.h 2 #include<iostream> 3 using namespace std; 4 5 class IntMatrix{ 6 public: 7 IntMatrix(int ir,int ic); 8 IntMatrix(int n);//转换构造函数:将整型n转化为n阶单位阵。 9 IntMatrix(const IntMatrix& m);//拷贝构造函数 10 friend ostream& operator<<(ostream&,const IntMatrix&); 11 friend istream& operator>>(istream&,IntMatrix&); 12 IntMatrix& operator=(const IntMatrix& m); 13 IntMatrix operator+(const IntMatrix& m); 14 ~IntMatrix(); 15 private: 16 int **p; 17 int r; 18 int c; 19 }; 20 21 //matrix.cpp 22 #include"matrix.h" 23 int i,j; 24 IntMatrix::IntMatrix(int ir,int ic):r(ir),c(ic) 25 { 26 p=new int*[r]; 27 for(i=0;i<r;i++) 28 p[i]=new int[c]; 29 cout<<"<define a ( "<<r<<","<<c<<" )matrix.>"<<endl; 30 } 31 IntMatrix::IntMatrix(int n):r(n),c(n) 32 { 33 p=new int*[r]; 34 for(i=0;i<r;i++) 35 p[i]=new int[c]; 36 for(i=0;i<r;i++) 37 for(j=0;j<c;j++) 38 if(i!=j) 39 p[i][j]=0; 40 else 41 p[i][j]=1; 42 cout<<"<define a ("<<n<<") identity matrix.>"<<endl; 43 } 44 IntMatrix::IntMatrix(const IntMatrix& m) 45 { 46 r=m.r; 47 c=m.c; 48 delete p; 49 p=new int*[r]; 50 for(i=0;i<r;i++) 51 p[i]=new int[c]; 52 for(i=0;i<r;i++) 53 for(j=0;j<c;j++) 54 p[i][j]=m.p[i][j]; 55 } 56 IntMatrix& IntMatrix::operator=(const IntMatrix& m) 57 { 58 if(this==&m) return *this; 59 if(r!=m.r||c!=m.c) cout<<"Only homography matrix can be added."<<endl; 60 else 61 { 62 delete p; 63 p=new int*[r]; 64 for(i=0;i<r;i++) 65 p[i]=new int[c]; 66 for(i=0;i<r;i++) 67 for(j=0;j<c;j++) 68 p[i][j]=m.p[i][j]; 69 } 70 return *this; 71 } 72 IntMatrix IntMatrix::operator+(const IntMatrix& m) 73 { 74 if(r!=m.r||c!=m.c) 75 { 76 cout<<"Only homography matrix can be added."<<endl; 77 return *this; 78 } 79 else{ 80 IntMatrix mt(r,c); 81 for(i=0;i<r;i++) 82 for(j=0;j<c;j++) 83 mt.p[i][j]=p[i][j]+m.p[i][j]; 84 return mt; 85 } 86 } 87 IntMatrix::~IntMatrix() 88 { 89 for(i=0;i<c;i++) 90 delete []p[i]; 91 delete []p;//[]p代表p[i],一维数组。 92 cout<<"<the matrix is deleted!>"<<endl; 93 } 94 istream& operator>>(istream& input,IntMatrix& m) 95 { 96 int ir=m.r,ic=m.c; 97 cout<<"Input the elements according to the row:"<<endl; 98 for(i=0;i<ir;i++) 99 for(j=0;j<ic;j++) 100 input>>m.p[i][j]; 101 return input; 102 } 103 ostream& operator<<(ostream& output,const IntMatrix& m) 104 { 105 int outr=m.r,outc=m.c; 106 for(i=0;i<outr;i++) 107 { 108 for(j=0;j<outc;j++) 109 output<<m.p[i][j]<<" "; 110 output<<endl; 111 } 112 return output; 113 } 114 115 //main.cpp 116 #include<iostream> 117 #include "matrix.h" 118 119 using namespace std; 120 121 int main() 122 { 123 int n; 124 cout<<"The order of the Square Matrix:"; 125 cin>>n; 126 IntMatrix m0(n,n); 127 cin>>m0; 128 cout<<"m0:"<<endl; 129 cout<<m0; 130 IntMatrix m1(n,n); 131 m1=m0; 132 cout<<"m1=m0"<<endl<<"m1:"<<endl; 133 cout<<m1; 134 IntMatrix m2(n,n); 135 m2=m0+IntMatrix(n); 136 cout<<"m2=m0+Intmatrix("<<n<<")"<<endl<<"m2:"<<endl; 137 cout<<m2; 138 return 0; 139 }
原文:https://www.cnblogs.com/satellite2021/p/14820213.html