大家来帮忙阿!小弟搞不定了!
贾延平 2002-04-08 02:54:58 程序如下:
Matrix.h:
#ifndef MATRIX_H
#define MATRIX_H
#include<iostream>
using namespace std;
template<class T>
class Matrix{
friend ostream& operator<<(ostream& out,const Matrix<T>& m);
public:
Matrix(int r = 0,int c = 0);
Matrix(const Matrix<T>& m);//copyconstructor
~Matrix(){delete [] element;}
int Rows() const {return rows;}
int Columns() const {return cols;}
T& operator()(int i,int j) const;
Matrix<T>& operator=(const Matrix<T>& m);
Matrix<T> operator+() const;
Matrix<T> operator+(const Matrix<T>& m) const;
Matrix<T> operator-() const;
Matrix<T> operator-(const Matrix<T>& m) const;
Matrix<T> operator*(const Matrix<T>& m) const;
Matrix<T>& operator+=(const T &x);
private:
class BadInitializers{
public:
BadInitializers(){
cerr<<"失败";
}
};
int rows,cols;
T* element;
};
template<class T>
ostream& operator<<( ostream& out,const Matrix<T>& m)
{
for(int i = 0;i < m.rows;i++)
for(int j = 0;j < m.cols;j++){
out<<m.element[i*m.rows+j];
out<<' ';
}
out<<endl;
return out;
}
#endif
Matrix.cpp:
#include"Matrix.h"
template<class T>
Matrix<T>::Matrix(int r,int c)
{
if(r<0||c<0)
throw BadInitializers();
if((!r||!c)&&(r||c))
throw BadInitializers();
rows=r;
cols=c;
element = new T[r*c];
}
template<class T>
Matrix<T>::Matrix(const Matrix<T>& m)
{
rows = m.rows;
cols = m.cols;
int s = rows*cols;
element = new T[s];
for(int i=0;i<s;i++)
element[i] = m.element[i];
}
template<class T>
T& Matrix<T>::operator()(int i,int j) const
{
if(i<1||i>rows||j<1||j>cols) throw OutOfBounds();
return element(i-1)*cols+j-1];
}
template<class T>
Matrix<T> Matrix<T>::operator+() const
{
Matrix<T> m(rows,cols);
for(int i = 0;i<rows*cols;i++)
m.element[i] = element[i];
return m;
}
template<class T>
Matrix<T> Matrix<T>::operator+(const Matrix<T>& m) const
{
if(rows != m.rows||cols != m.cols)
throw SizeMismatch();
Matrix<T> w(rows,cols);
for(int i = 0;i<rows*cols;i++)
w.element[i] = element[i] + m.element[i];
return w;
}
template<class T>
Matrix<T> Matrix<T>::operator-() const
{
Matrix<T> w(rows,cols);
for(int i = 0;i<rows*cols;i++)
w.element[i] = -element[i];
return w;
}
template<class T>
Matrix<T> Matrix<T>::operator-(const Matrix<T>& m) const
{
if(rows != m.rows||cols != m.cols)
throw SizeMismatch();
Matrix<T> w(rows,cols);
for(int i = 0;i<rows*cols;i++)
w.element[i] = element[i] - m.element[i];
return w;
}
template<class T>
Matrix<T> Matrix<T>::operator*(const Matrix<T> &m) const
{
if(cols != m.rows)throw SizeMismatch();
Matrix<T> w(rows,m.cols);
int ct = 0,cm = 0,cw = 0;
for(int i = 1;i<=rows;i++){
for(int j = 1;j<=m.cols;j++){
T sum = element[ct]*m.element[cm];
for(int k = 2;k <= cols;k++){
ct++;
cm += m.cols;
sum += element[ct] * m.element[cm];
}
w.element[cw++] = sum;
ct -= cols - 1;
cm = j;
}
ct +=cols;
cm = 0;
}
return w;
}
测试的test.cpp:
#include<iostream>
#include"Matrix.h"
using namespace std;
int main()
{
Matrix<int>* s=new Matrix<int>(7,4);
cout<<*s;
return 1;
}
为什么调不通?????