#ifndef _ARRAY1D
#define _ARRAY1D
#include<iostream.h>
/* 矩阵类*/
template<class T>
class CMatrix {
public :
CMatrix(int r = 0, int c = 0);
CMatrix(const CMatrix<T>& m); //复制构造函数
~CMatrix() {delete [] element;}
int Rows() const {return rows;}
int Columns() const {return cols;}
T& operator()(int i, int j) const;
CMatrix<T>& operator=(const CMatrix<T>& m);
CMatrix<T> operator+() const; // 一元加法
CMatrix<T> operator+(const CMatrix<T>& m) const;
CMatrix<T> operator-() const; //一元减法
CMatrix<T> operator-(const CMatrix<T>& m) const;
CMatrix<T> operator*(const CMatrix<T>& m) const;
CMatrix<T>& operator+=(const T& x);
friend ostream& operator<<(ostream& out, const CMatrix<T>& w);
private :
int rows, cols; // 矩阵维数
T *element; // 元素数组
};
template<class T>
CMatrix<T>::CMatrix(int r, int c)
{// 类CMatrix的构造函数
// 验证r和c的合法性
if (r >0 || c>0)
{
// 创建矩阵
rows = r;
cols=c;
element = new T [r*c];
}
}
template<class T>
T& CMatrix<T>::operator()(int i, int j) const
{// 返回一个指向元素( i , j )的引用
return element[(i-1)*cols+j-1];
}
template<class T>
CMatrix<T> CMatrix<T>::operator-(const CMatrix<T>& m) const
{// 返回(*this) - m.
if (rows==m.rows&&cols== m.cols)
{
// 创建结果矩阵w
CMatrix<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>
ostream& operator<<(ostream& out, const CMatrix<T>& w)
{
for(int i=0;i<w.rows*w.cols;i++)
{
out<<w.element[i]<<" ";
if((i+1)%w.cols==0)
out<<endl;
}
return out;
}
#endif
主函数的调用:
#include "Array1D.h"
void main()
{
CMatrix<int> matrix(2, 3);
matrix(1,1)=3;
matrix(1,2)=10;
matrix(1,3)=24;
matrix(2,1)=20;
matrix(2,2)=15;
matrix(2,3)=27;
cout<<matrix(1,3)<<endl;
cout<<"所有矩阵的值为:"<<endl;
cout<<matrix<<endl;
}