友元
关键字:friend
友元的实现:全局函数做友元; 类做友元; 成员函数做友元。
.1全局函数做友元
class Point
{
private:
double x, y;
public:
Point(double xx, double yy);
friend int Distance(Point &a, Point &b);//Distance作为Point的朋友,可以访问私有成员
};
Point ::Point (double xx, double yy){
x = xx;
y = yy;
}
int Distance(Point &a, Point &b)
{
double d;
d = sqrt((a.x - b.x)*(a.x - b.x)+(a.y - b.y)*(a.y - b.y));
return (int)d;
}
.2类做友元
.3成员函数做友元
class Buliding;
class Goodgay
{
public:
Goodgay();
void visit();//让visit函数可以访问Buliding 中私有成员
void visit2();//让visit2函数不可以访问Buliding 中私有成员
private:
Buliding *buliding;
};
class Buliding
{
friend void Goodgay::visit();//goodgay中的visit成员函数是Buliding好朋友,可以访问私有内容
public:
Buliding();
public:
string m_sittingroom;
private:
string m_bedroom;
};
Buliding::Buliding()
{
this->m_sittingroom = "客厅";
this->m_bedroom = "卧室";
}
Goodgay::goodgay()
{
buliding = new Buliding;
}
void goodgay:;visit()
{
cout<<buliding->m_sittingroom<<endl;
cout<<buliding->m_bedroom<<endl;
}
void goodgay:;visit2()
{
cout<<buliding->m_sittingroom<<endl;
cout<<buliding->m_bedroom<<endl;
}