定义了两个类
class Vector
{
public:
Vector(int);
~Vector(){delete []v;}
Vector(Vector &);
void Display();
int &Elem(int);
friend Vector Multiply(Matrix &m,Vector &v);//友元
protected:
int*v;
int sz;
};
class Matrix
{
public:
Matrix(int,int);
~Matrix(){delete []m;}
Matrix(Matrix &);
int &Elem(int,int);
friend Vector Multiply(Matrix &m,Vector &v);//友元
protected:
int *m;
int szl;
int szr;
};
Matrix::Matrix(Matrix &mat)
{
szl=mat.szl;
szr=mat.szr;
m=new int(mat.szl*mat.szr);
memcpy((void*)m,(void *)mat.m,szl*szr*sizeof(int));
}
int & Matrix::Elem(int i,int j)
{
if(i<0||j<0||i>=szl||j>=szr)
cerr<<"Matrix index out of range"<<endl;
return m[szr*i+j];
}
Vector Multiply(Matrix &m,Vector &v) //友元定义
{
if(m.szr!=v.sz)
{
cerr<<"bad multiply matrix with vector"<<endl;
exit(1);
}
Vector r(v.sz);
for(int i=0;i<m.szl;i++)
{
r.v[i]=0;
for(int j=0;j<m.szr;j++)
r.v[i]+=m.m[m.szr*i+j]*v.v[i];
}
return r;
}
结果编译连接出错了:错误原因:
:\programe\1506\1506.cpp(12) : error C2061: syntax error : identifier 'Matrix'
D:\programe\1506\1506.cpp(95) : error C2248: 'sz' : cannot access protected member declared in class 'Vector' //我在两个类中都声明了的啊,
怎么还是不能用保护数据成员呢,为什么???????????????
D:\programe\1506\1506.cpp(15) : see declaration of 'sz'
D:\programe\1506\1506.cpp(100) : error C2248: 'sz' : cannot access protected member declared in class 'Vector'
D:\programe\1506\1506.cpp(15) : see declaration of 'sz'
D:\programe\1506\1506.cpp(103) : error C2248: 'v' : cannot access protected member declared in class 'Vector'
D:\programe\1506\1506.cpp(14) : see declaration of 'v'
D:\programe\1506\1506.cpp(105) : error C2248: 'v' : cannot access protected member declared in class 'Vector'
D:\programe\1506\1506.cpp(14) : see declaration of 'v'
D:\programe\1506\1506.cpp(105) : error C2248: 'v' : cannot access protected member declared in class 'Vector'
D:\programe\1506\1506.cpp(14) : see declaration of 'v'