矩阵类

矩阵类

自己编写的一个矩阵类,个人感觉从文件中读取矩阵和将矩阵写入文件这两个函数作用大些。
收获:1. 对类的static成员函数的作用有所了解。
           2. 对文件的读写操作熟练了一些。clear,seekg等
           3. 对异常处理的初级应用。
下面把代码贴出来吧

// Matrix.h
// 矩阵类定义

#ifndef MATRIX_H
#define  MATRIX_H
#include 
< iostream >
#include 
< string >
// using namespace std; 一般头文件中使用完全限定域名字,而不是包含命名空间,防止重复包含头文件时造成的资源浪费

class  Matrix 
{
    
//从流中读入矩阵
    friend std::istream& operator >> (std::istream& is, Matrix A);
    
//输出矩阵
    friend std::ostream& operator << (std::ostream& os, const Matrix& A);
    
//将矩阵输出到名为str的文件中
    friend void print_file(const Matrix&A,const char* str);
public:
    
//定义空矩阵
    Matrix() {elems = NULL; row = 0; col = 0;};
    
//定义m*n零矩阵
    Matrix(int m, int n);
    
//定义m*n矩阵,由a初始化
    Matrix(int m, int n, double *a, int size = 0);    
    
//复制构造函数
    Matrix(const Matrix& B);
    
//从文件str中读取矩阵
    Matrix(const char* str);

    
~Matrix() {delete[]elems; row = 0; col = 0;    };
    
    
//重载算数操作符
    Matrix& operator = (Matrix& B);
    Matrix 
operator +(const Matrix&B)const;
    Matrix 
operator -(const Matrix&B)const;
    Matrix 
operator *(const Matrix&B)const;

    
//返回矩阵第i行第j列元素
    double& operator()(int i,int j)const;
    
    
double get_row()const {return row;};
    
double get_col()const {return col;};
    
    
//矩阵转置
    Matrix& trans()const;
    
protected:
private:
    
double* elems;
    
int row, col;
}
;

#endif

  1 // Matrix.cpp
  2 // 函数实现
  3
  4 #include  " Matrix.h "
  5 #include  < iostream >
  6 #include  < fstream >
  7 #include  < sstream >
  8 #include  < string >
  9 #include  < stdexcept >
 10
 11 using   namespace  std;
 12
 13 // 重载下标操作符,返回A[i,j]
 14 double &  Matrix:: operator ()( int  i, int  j) const
 15 {
 16    if(i<0 || i >= row || j < 0 || j >= col)
 17        throw out_of_range("The suffix is out of range");
 18    
 19    return elems[i*col+j];
 20}

 21
 22 // 从输入流中读入矩阵
 23 istream &   operator   >> (istream &   is , Matrix & A)
 24 {
 25    for(int i = 0; i != A.get_row(); ++i)
 26        for(int j = 0; j != A.get_col(); ++j)
 27            is >> A(i,j);
 28    return is;
 29}

 30
 31 // 输出矩阵
 32 ostream &   operator   << (ostream &  os,  const  Matrix &  A)
 33 {
 34    for(int i = 0; i != A.get_row(); ++i)
 35    {
 36        for(int j = 0; j != A.get_col(); ++j)
 37            os << A(i,j) << " ";
 38        cout <<endl;
 39    }

 40    cout << "------------------------" <<endl;
 41
 42    return os;
 43    
 44}
;
 45
 46 // 将矩阵A输出到文件str中
 47 void  print_file( const  Matrix & A, const   char *  str)
 48 {
 49    ofstream outfile("Matrix_out.txt",ios::app);
 50    if(!outfile)
 51        throw domain_error("Cannot open this file.");
 52    
 53    for(int i = 0; i != A.row; ++i)
 54    {
 55        for(int j = 0; j!= A.col; ++j)
 56            outfile << A(i,j);
 57        outfile << endl;
 58    }

 59    outfile << "----------------------"<<endl;            
 60
 61    outfile.clear();
 62    outfile.close();
 63}

 64
 65 // 构造m*n零矩阵
 66 Matrix::Matrix( int  m,  int  n):row(m),col(n)
 67 {
 68    if(m <1 || n <1)
 69        throw out_of_range("The row or column number should be larger than 0.");
 70    elems = new double[m*n];
 71    for(int i = 0; i != m*n; ++i)
 72        elems[i] = 0;
 73}

 74
 75 // 构造m*n矩阵,从数组a中读入数据存储到矩阵中
 76 Matrix::Matrix( int  m,  int  n, double *  a,  int  size):row(m),col(n)
 77 {
 78    if(m <0 || n<0 || size < m*n)
 79        throw out_of_range("The suffix or size are out of range");
 80
 81    elems = new double[m*n];    
 82    for(int i = 0; i != m*n; ++i)
 83        elems[i] = a[i];
 84
 85}
;
 86
 87 // 从文件中读入矩阵
 88 Matrix::Matrix( const   char *  str)
 89 {
 90    //忘了刚开始的行列初始化,导致错误,寻找了半天。
 91    row = 0;
 92    col = 0;
 93    
 94    ifstream infile(str,ios::in);
 95    if(!infile)
 96    {
 97        throw domain_error("Cannot find this file.");
 98    }

 99
100    char ch = ' ';
101    //计算列数
102    while(infile.get(ch) && ch != '\n')
103    {
104        if(ch == ' ')  ++col;        
105    }

106    ++col;    
107    
108    //计算行数
109    infile.clear(); //在这里这个语句不必要
110    infile.seekg(0,ios::beg);//千万不能忘了重定位到文件头
111    while(infile.get(ch))
112    {
113        if(ch == '\n'++row;
114    }

115    ++row;
116
117    infile.clear();//已经读到文件尾时想重新定位到文件头必须有这条语句
118    infile.seekg(0,ios::beg);
119    
120    elems = new double[row*col];
121    int i = 0;
122    while(i != row*col)
123        infile >> elems[i++];
124
125    infile.clear();
126    infile.close();
127    
128}

129
130 // 矩阵复制构造函数
131 Matrix::Matrix( const  Matrix &  B):row(B.row),col(B.col)
132 {
133    if((row != B.row) || (col != B.col)) 
134        throw invalid_argument("The Matrix should be matched.");
135    
136    elems = new double[row*col];
137    for(int i = 0; i != row*col; ++i)
138        elems[i] = B.elems[i];
139    
140}
;
141
142 // 重载矩阵赋值操作符    
143 Matrix &  Matrix:: operator   =  (Matrix &  B)
144 {
145    
146    if((row != B.row) || (col != B.col)) 
147        throw invalid_argument("The matrix should be matched.");
148    row = B.row;
149    col = B.col;
150    elems = new double[row*col];
151    for(int i = 0; i != row*col; ++i)
152        elems[i] = B.elems[i];
153
154    return *this;
155}
;
156
157 // 重载矩阵相加操作符
158 Matrix Matrix:: operator + ( const  Matrix &  B) const
159 {
160    if((row != B.row) || (col != B.col)) 
161        throw invalid_argument("The matrix should be matched");    
162
163    Matrix& T = * new Matrix;
164    T.row = row;
165    T.col = col;
166    T.elems = new double[row*col];
167
168    for(int i = 0; i != row*col; ++i)
169        T.elems[i] = elems[i] + B.elems[i];
170    return T;
171
172}
;
173
174 // 重载矩阵相减操作符
175 Matrix Matrix:: operator - ( const  Matrix &  B) const
176 {
177    if((row != B.row) || (col != B.col)) 
178        throw invalid_argument("The matrix should be matched");    
179
180    Matrix& T = * new Matrix;
181    T.row = row;
182    T.col = col;
183    T.elems = new double[row*col];
184
185    for(int i = 0; i != row*col; ++i)
186        T.elems[i] = elems[i] - B.elems[i];
187    return T;
188
189}
;
190
191 // 重载矩阵相乘操作符
192 Matrix Matrix:: operator   * ( const  Matrix &  B) const
193 {
194    if( col != B.row)
195        throw invalid_argument("The matrix should be matched.");    
196
197    Matrix& T = *new Matrix;
198    T.row = row;
199    T.col = B.col;
200    T.elems = new double[T.row * T.col];
201
202    for(int i = 0; i != T.row; ++i)
203        for(int j = 0; j != T.col; ++j)
204        {
205            T.elems[i * T.col + j] = 0;
206            for(int k = 0; k != col; ++k)
207                T.elems[i * T.col + j] += elems[i * col + k] * B.elems[k*B.col + j];
208        }

209
210    return T;
211}
;
212     
213 // 转置矩阵
214 Matrix &  Matrix::trans() const
215 {
216    Matrix& T = *new Matrix; //new 返回的是指针,需要解引用
217    T.row = col;
218    T.col = row;
219    T.elems = new double[row*col];
220    for(int i = 0; i != T.row; ++i)
221        for(int j = 0; j != T.col; ++j)
222            T.elems[i*T.col + j] = elems[j*col + i];
223    return T;
224}

 1 // Mainfun.cpp
 2 // 测试编写的矩阵类
 3 #include  " Matrix.h "
 4 #include  < iostream >
 5 #include  < string >
 6 #include  < fstream >
 7 #include  < cstdlib >  
 8 #include  < stdexcept >
 9
10 using   namespace  std;
11
12 int  main()
13 {
14    double d[12= {1,2,3,4,5,6,7,8,1,2,3,4};
15    double d2[12= {1,2,3,4,1,2,3,4,5,6,7,8};
16    Matrix A(3,4,d,12);
17    Matrix B(3,4,d2,12);
18    Matrix C= B.trans();
19    
20    cout << "A = \n" << A << "B = \n" << B << "C = \n" <<C<<endl;
21    cout << "A + B \n" << A + B << "B*C \n" << B*<<endl;
22
23    //将矩阵输出到文件Matrix_out.txt中
24    print_file(A,"Matrix_out.txt");
25    
26    //从文件"Matrix_in.txt"中读取矩阵
27    Matrix D("Matrix_in.txt");
28        cout << D <<endl;    
29
30    //异常处理的写起来太繁琐了,只示例一个,其他省略了。
31    try
32    {
33        Matrix D(0,3);
34    }

35    catch(out_of_range& err)
36    {
37        cerr << err.what() <<endl;
38    }
    
39
40    system("pause");
41    return 0;
42}

43

你可能感兴趣的:(矩阵类)