允许访问私有数据的朋友--友元
友元可以访问与其好友关系的类中的私有成员,友元包括友元函数和友元类。
可以访问私有数据的友元函数
如果在本类以外的其它地方定义了一个函数,在类体中用friend对其进行声明,此函数就称为本类的友元函数,友元函数可以访问这个类中的私有成员。
将普通函数声明为友元函数
例1:使用友元函数访问私有数据
#include <iostream>
using namespace std;
class Time
{
public:
Time(int, int, int);
friend void display(Time&);
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, 11, 13);
display(t1);
return 0;
}
用友元成员函数访问私有数据
friend函数不仅可以是一般函数,而且可以是另一个类中的成员函数。
例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&);
private:
int month, day, year;
};
Time::Time(int h, int m, int s)
{
hour = h;
minute = m;
sec = s;
}
void Time::display(Date& d)
{
cout << d.month << "/" << d.day << "/" << d.year << endl;
cout << hour << ":" << minute << ";" << sec << endl;
}
Date::Date(int m, int d, int y)
{
month = m;
day = d;
year = y;
}
int main()
{
Time t1(11, 12, 13);
Date d1(12, 14, 2012);
t1.display(d1);
return 0;
}
一个函数可以被多个类声明为朋友,这样就可以引用多个类中的私有数据。
友元类
不仅可以将一个函数声明为一个类的朋友,而且可以将一个类声明为另一个类的朋友,声明友元类的一般形式为 friend 类名;
1、友元类的关系是单向的而不是双向的。
2、友元的关系不能传递。
实际工作中,除非确有必要,一般并不把整个类名声明为友元类,而只将确实有需要的成员函数声明为友元类,这样更安全。
类模板
1、声明类模板时要增加一行 template <class 类型参数名>
2、原有的类型名换成虚拟类型参数名。如果说类是对象的抽象,对象是类的实例,则类模板是类的抽象,类是类模板的实例。

被折叠的 条评论
为什么被折叠?



