Oct 8, 2009 at 3:37pm UTC
My C++ program as follows :
# include "iostream.h"
# include "stdlib.h"
class CMatrix
{
double *p;
int i,j;
public :
CMatrix(){i=0;j=0;}
CMatrix(int s,int t)
{
i=s;j=t;p=new double[i*j];
}
~CMatrix() {delete []p;}
int Geti();
int Getj();
void SetMatrix();
double& operator ()(int s,int t);
friend CMatrix& operator* (CMatrix& A,CMatrix B);
friend ostream& operator<< (ostream& out,CMatrix& M);
};
int CMatrix::Geti()
{
return i;
}
int CMatrix::Getj()
{
return j;
}
void CMatrix::SetMatrix()
{
cout<<"input the Matrix number:"<<endl;
for(int r=0;r<i*j;r++)
cin>>p[r];
}
double& CMatrix::operator () (int s,int t)
{
if(s<0 || s>=i || t<0 || t>=j )
{
cout<<"Error\n";
exit(1);
}
return p[s*i+j];
}
CMatrix& operator * (CMatrix& A,CMatrix& B) //Here cannot be compiled .
{
int m=A.Geti(), n=B.Getj();
static CMatrix C;
for(int s=0;s<m;s++)
{
for(int t=0;t<n;t++)
{
int k=0;
for(k=0;k<A.Getj();k++)
C(s,t)+=A(s,k)*B(k,t);
}
}
return C;
}
ostream& operator << (ostream& out,CMatrix& M)
{
out.precision(3);
for(int s=0;s<M.i;s++)
{
for(int t=0;t<M.j;t++)
{
out.width(8);
out<<M.p[M.j*s+t];
}
out<<endl;
}
return out;
};
void main()
{
CMatrix m1(2,3),m2(3,2),m3;
m1.SetMatrix();
m2.SetMatrix();
m3=m1*m2; //show error C2593: 'operator *' is ambiguous .
cout<<m3;
}
Oct 8, 2009 at 4:01pm UTC
You did not overload operator* for the matrix class. I recommend that you go read your c++ book on operator overloading or find some tutorials on the subject. The default operator* only understands how to multiply built in types, not user defined types.