| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 535 人关注过本帖
标题:关于友元使用保护数据成员
只看楼主 加入收藏
karlzhouzhi
Rank: 1
等 级:新手上路
帖 子:70
专家分:0
注 册:2005-12-25
收藏
 问题点数:0 回复次数:2 
关于友元使用保护数据成员

定义了两个类
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'

搜索更多相关主题的帖子: 成员 数据 
2006-02-10 00:55
柳儿
Rank: 6Rank: 6
等 级:贵宾
威 望:25
帖 子:1830
专家分:30
注 册:2004-9-23
收藏
得分:0 
以下是引用karlzhouzhi在2006-2-10 0:55:00的发言:

定义了两个类

class Matrix;
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;
};

楼主在类Vector定义之前,应该先声明类Matrix吧?

成功会使人骄傲。如果你骄傲自大,你就会停止学习。不学习,人就停止了进步
2006-02-10 10:23
karlzhouzhi
Rank: 1
等 级:新手上路
帖 子:70
专家分:0
注 册:2005-12-25
收藏
得分:0 

问题解决,谢谢关注:)

2006-02-10 10:38
快速回复:关于友元使用保护数据成员
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.019460 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved