友元函数
友元函数可以访问其他类中的私有成员,有助于数据共享,提高程序效率,但它又是对封装性的一个破坏,所以程序中不能大量使用友元
对友元函数的使用,和普通函数的使用方法一样,不需要在友元函数前面加上特殊标志。但是如果该友元函数是一个类的成员函数,则使用时还是要子啊友元函数前加上所属的类名。
#include <iostream>
using namespace std;
//对Date类的提前引用声明
class Date;
//定义Time类,声明display是其成员函数,形参是Date类对象的引用
class Time
{
public:
Time(int, int, int);
void display(Date &);
private:
int hour, minute, sec;
};
//定义类Date,声明Time类中的display函数为本类的友元成员函数
class Date
{
public:
Date(int, int, int);
friend void Time::display(Date&);
private:
int month, day, year;
};
//定义Time的构造函数
Time::Time(int h, int m, int s)
{
hour = h;
minute = m;
sec = s;
}
//定义类Time的成员函数display时,引用了Date类对象中私有成员,也引用了本类对象中的私有数据
void Time::display(Date & da)
{
cout << da.month << "/" << da.day << "/" << da.year << endl;
cout << hour << ":" << minute << ":" << sec << endl;
}
//定义类Date的构造函数
Date::Date(int m, int d, int y)
{
month = m;
day = d;
year = y;
}
int main()
{
Time t1(19, 23, 45);
Date d1(10, 9, 2020);
//调用t1中的display函数,实参是Date类对象d1
t1.display(d1);
system("pause");
return 0;
}
转载自:黑凤梨の博客