//友元关系提供了不同类或对象的成员函数之间,类的成员函数与一般函数之间进行数据共享的机制
class Point
{
public:
Point(int xx=0,int yy=0)
{
X=xx;
Y=yy;
}
int GetX()
{
return X;
}
int GetY()
{
return Y;
}
friend float fDist(Point &a,Point &b);//友元函数声明
private:
int X,Y;
};
float fDist(Point &p1,Point &p2) //友元函数实现
{
double x=double(p1.X-p2.X);
double y=double(p1.Y-p1.Y);
return float(sqrt(x*x+y*y));
}
int main()
{
Point myp1(1,1),myp2(4,5);
cout<<"The distance:";
cout<<fDist(myp1,myp2)<<endl;
}
//友元类
class A
{
public:
void Display()
{
cout<<x<<endl;
}
int GetX()
{
return x;
}
friend class B;//B类是A类的友元类
private:
int x;
}
class B
{
public:
void Set(int i)
void Display();
private:
A a;
};
void B::Set(int i)
{
a.x=i;//由于B是A的友元,所以在B的成员函数中可以访问A类对象的私有成员
}
友元关系
最新推荐文章于 2024-06-20 09:00:44 发布