# 友元类

1.友元函数

### 实现方式：friend 函数声明；

（1）.普通函数对类的局限性

（2）.友元函数的实现

#include <iostream>
#include <math.h>
using namespace std;

class point
{
public:
void set();
void showdata();
friend int distance(point &a,point &b);
private:
int x;
int y;
};

int distance(point &a,point &b)
{
int way;
way=sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
return way;
}

void point::showdata()
{
cout<<"x="<<x<<endl;
cout<<"y="<<y<<endl;
}

void point::set()
{
cout<<"输入x的值"<<endl;
cin>>x;
cout<<"输入Y的值"<<endl;
cin>>y;
}

int main()
{
point use_1,use_2;
use_1.set();
use_2.set();
use_1.showdata();
use_2.showdata();
cout<<"两点之间的距离为"<<distance(use_1,use_2)<<endl;
}

2.友元类

### 实现方式：friend 类申明；

（1）.友元类的实现

#include <iostream>
using namespace std;

class birth
{
public:
void set();
friend class people;
private:
int year;
int mon;
int day;
};

class people
{
public:
void set();
void show(birth &a);
friend class birth;
private:
char name;

};

void people::show(birth &a)
{
cout<<name<<endl;
cout<<a.year<<endl;
cout<<a.mon<<endl;
cout<<a.day<<endl;
}

void people::set()
{
cin>>name;
}

void birth::set()
{
cin>>year;
cin>>mon;
cin>>day;
}

int main()
{
people a;
birth b;
a.set();
b.set();
a.show(b);
}

（2）.友元类的单向性

#include <iostream>
using namespace std;

class birth
{
public:
void set();
private:
int year;
int mon;
int day;
};

class people
{
public:
void set();
void show(birth &a);
friend class birth;
private:
char name;

};

void people::show(birth &a)
{
cout<<name<<endl;
cout<<a.year<<endl;
cout<<a.mon<<endl;
cout<<a.day<<endl;
}

void people::set()
{
cin>>name;
}

void birth::set()
{
cin>>year;
cin>>mon;
cin>>day;
}

int main()
{
people a;
birth b;
a.set();
b.set();
a.show(b);
}

（3）.友元类的不可传递性

posted on 2019-09-29 10:16  zero-one  阅读(211)  评论(0编辑  收藏  举报