运算符的重载是C++多态性的一种体现。通过重载运算符,可以使代码变得更加简洁易懂,符合人的思维习惯。例如,通过对数组类重载+运算符,就可以直接完成数组之间的相加。
下面是数组类的定义:
template<class T>
class matrix
{
friend ostream& operator<<(ostream&, const matrix<T>&);//friend ostream& operator<<(ostream&, const matrix<T>& );
public:
matrix(int theRows=0, int theCols=0);
matrix(const matrix<T>& );
~matrix() {delete [] element; }
int rows() const {return theRows;}
int columns() const {return theCols;}
T& operator()(int i, int j) const;
matrix<T>& operator =(const matrix<T>& );
matrix<T> operator +() const;
matrix<T> operator +(const matrix<T>& ) const;
matrix<T> operator -() const;
matrix<T> operator -(const matrix<T>& ) const;
matrix<T> operator *(const matrix<T>& ) const;
matrix<T>& operator +=(const T&);
private:
int theRows,
theCols;
T *element;
};
重载+运算符:
template<class T>
matrix<T> matrix<T>::operator +(const matrix<T>& m) const
{
matrix<T> w(theRows,theCols);
for(int i=0;i<theRows*theCols;i++)
w.element[i]=element[i]+m.element[i];
return w;
}
重载()运算符,用于完成矩阵的索引与值得对应,可用与取值和赋值:
template<class T>
T& matrix<T>::operator ()(int i,int j) const
{
return element[(i-1)*theCols+j-1];
}
template<class T>
重载=运算符,实现矩阵之间的相等,可将一个矩阵赋值给另一个:
template<class T>
matrix<T>& matrix<T>::operator =(const matrix<T>& m )
{
if(this!=&m)
{
delete [] element;
theRows=m.theRows;
theCols=m.theCols;
element=new T[theRows*theCols];
copy(m.element,m.element+theRows*theCols,element);
}
return *this;
}
重载*运算符,用于完成矩阵间的乘法:
template<class T>
matrix<T> matrix<T>::operator *(const matrix<T>& m) const
{
matrix<T> w(theRows,m.theCols);
int ct=0,cm=0,cw=0;
for(int i=1;i<=theRows;i++)
{
for(int j=1;j<=m.theCols;j++)
{
T sum=element[ct]*m.element[cm];
for(int k=2;k<=theCols;k++)
{
ct++;
cm+=m.theCols;
sum+=element[ct]*m.element[cm];
}
w.element[cw++]=sum;
ct-=theCols-1;
cm=j;
}
ct+=theCols;
cm=0;
}
return w;
}
重载<<运算符,用于实现矩阵的输出:
ostream& operator<<(ostream& out ,const matrix<int>& a)
{
int rows=a.theRows;
int cols=a.theCols;
int k=0;
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
out<<a.element[k++]<<' ';
out<<endl;
}
return out;
}
这里的模板类型T必须定为具体类型,否则编译不通过。
调用程序:
matrix<int> x(3,2),y,z,xd(2,3),mn;//实例化矩阵对象
for(int i=0;i<=3;i++)
for(int j=0;j<=2;j++)
x(i,j)=2*i+j; //通过()操作符给矩阵赋值
y=x;//调用=运算符
z=y+x;//调用+运算符
//矩阵转置
for(int m=0;m<=3;m++)
for(int n=0;n<=2;n++)
xd(n,m)=x(m,n);
mn=x*xd;//调用*运算符
//调用<<运算符
cout<<x<<endl;
cout<<y<<endl;
cout<<z<<endl;
cout<<xd<<endl;
cout<<mn<<endl;
程序输出: