1 #include <iostream.h>
2 template<class T>
3 class Matrix
4 {
5 public:
6 Matrix(int r=0,int c=0);
7 Matrix(Matrix<T> &m);
8 ~Matrix()
9 {
10 delete []melem;
11 }
12 void input();
13 void print();
14 T & operator ()(int i,int j);
15 void transmat(Matrix<T> &,Matrix <T> &);
16 private:
17 int rows,cols;
18 T *melem;
19 };
20 template <class T>
21 Matrix<T>::Matrix(int r,int c)
22 {
23 rows=r;
24 cols=c;
25 melem=new T[r*c];
26 }
27 template <class T>
28 Matrix<T>::Matrix(Matrix<T> &m) //构造函数
29 {
30 rows =m.rows;
31 cols =m.cols;
32 melem =new T[rows*cols];
33 for(int i =0 ; i<rows *cols ; i++)
34 melem [i]=m.melem[i];
35 }
36 template<class T>
37 T &Matrix <T> ::operator () (int i,int j) //取元素运算
38 {
39 return melem [(i-1)*cols +j-1];
40 }
41
42 template<class T>
43 void Matrix<T>::input()
44 {
45 for(int i=0;i<cols*rows ;i++)
46 cin>>melem [i];
47 }
48 template<class T>
49 void Matrix<T>::print()
50 {
51 for (int i=0;i<rows*cols;i++)
52 {
53 if(i%cols==0)
54 cout<<endl;
55 cout<<melem [i]<<'\t';
56 }
57
58 }
59 template <class T>
60 void Matrix<T>::transmat(Matrix<T>&a, Matrix <T> &b)
61 {
62 int i,j;
63 for(i=1;i<=a.rows;i++)
64 for(j=1;j<=a.cols;j++)
65 {
66 b(j,i)=a(i,j);
67 }
68 }
69 int main()
70 {
71 Matrix<int > A(3,2) ,B(2,3) ;
72 A.input();
73 cout<<"A:";
74 A.print();
75 A.transmat(A,B);
76 cout<<endl<<"B:";
77 B.print();
78 cout<<endl;
79 return 0;
80 }