1.一般友元函数【就像可访问私有成员的一般函数】:
一个例子:
#include <iostream>
using namespace std;
class Time{
public:
Time( int, int, int);
friend void display(Time &);//先声明,使一般函数display可以访问本类的私有成员
private:
int hour, minute, sec;
};
Time::Time(int h, int m, int s)
{
hour = h;
minute = m;
sec = s;
}
void display(Time &t)
{
cout << t.hour <<':'<< t.minute << ':' << t.sec <<endl;
}
int main()
{
Time t1(10,13,56);
display(t1);
return 0;
}
2.友元成员函数:一个例子【对其他类的成员函数不设防】
#include <iostream>
using namespace std;
class Date;
class Time{
public:
Time( int, int, int);
void display(Date &);
private:
int hour, minute, sec;
};
class Date{
public:
Date( int, int, int);
friend void Time::display(Date &); //先声明,对它不设防。要记得制定是那个类的【Time::】
private:
int year, month, day;
};
Time::Time(int h, int m, int s)
{
hour = h;
minute = m;
sec = s;
}
Date::Date(int y, int m, int d)
{
year = y;
month = m;
day = d;
}
void Time::display(Date &d)
{
cout << d.year <<'.'<< d.month << '.' << d.day <<endl;
cout << hour <<':'<< minute << ':' << sec <<endl;
}
int main()
{
Time t1(10,13,56);
Date d1(2013,9,26);
t1.display(d1);
}
【提示:在这里用到了类的提前声明,解决两个类相互包含的问题。
累得提前声明只能用在互相包含的声明中,而不能用在定义之前,例如class Date; Date d1;是错误的,因为提前声明不能让编译器知道类的大小。】
3.友元类:如
class A{............
friend B;
........};//则B拥有访问A的私有成员的权限!
一个例子:
class Date{
public:
Date( int, int, int);
//friend void Time::display(Date &); //先声明,对它不设防。要记得制定是那个类的【Time::】
friend Time;
private:
int year, month, day;
};
只是把上面的friend void Time::display(Date &),换成为friend Time即可。所以Time 可以访问 Date的数据。
4.关于友元:
A友元的关系是单向的,而非双向的,如上例子,A不能访问B的私有成员。
B友元的关系不能传递:若B是A的友元类,C是B的友元类,那么C不是A的友元类【除非额外声明】
C为了安全性,不使用友元类,多使用友元函数。