- 全局函数做友元
#include<iostream>
using namespace std;
class Person
{
friend void guy(Person &p);//全局函数做友元可以访问私有内容
public:
Person()
{
num = 23;
age = 18;
}
int num;
private:
int age;
};
void guy(Person &p)//全局函数做友元
{
cout << p.age << endl;
}
int main()
{
Person p1;
guy(p1);
system("pause");
return 0;
}
- 类做友元
#include<iostream>
using namespace std;
class Person
{
friend class School;//类做友元,可以访问到Person中的私有成员
public:
Person()
{
num = 23;
age = 18;
}
int num;
private:
int age;
};
class School
{
public:
School()
{
cout << p1.age << endl;
}
private:
Person p1;
};
3.成员函数做友元
#include<iostream>
using namespace std;
class Person;
class School
{
public:
School();
void show();//必须在Person类前被声明
private:
Person * p1;
};
class Person
{
friend void School::show();
public:
Person();
int num;
private:
int age;
};
void School::show()
{
cout << p1->num << endl;
cout << p1->age << endl;
}
School::School()
{
p1 = new Person;
}
Person::Person()
{
num = 23;
age = 18;
}
int main()
{
School s1;
s1.show();
system("pause");
return 0;
}
School::show()必须在Person类之前被声明
首先声明Person类,定义School类以及声明show()函数,在show()使用Person的成员之前必须声明Person。接下来定义Person类和对show()的友元声明,最后定义show(),应该是类外定义,此时才可以使用Person的成员