1.友元函数
1.友元函数不是当前类中的成员函数,它既可以是一个不属于任何类的一般函数,也可以是另外一个类的成员函数。将一个函数声明为一个类的友元函数后,不仅可以通过对象名访问类的公有成员,而且可以通过对象名访问类的私有成员和受保护成员。
2.两种语法形式:
(1)非成员函数作为友元函数的格式如下:
friend 返回值类型 函数名(参数表)
(2)类的成员函数作为友元函数格式如下:
friend 返回值类型 类名::函数名(参数表)
代码示例:
编写一个程序,输出年月日时分秒。使得程序中的display函数作为类外的普通函数,
并在Time类和Date类中将display声明为友元函数。在主函数中调用display函数,
display函数分别引用Time类和Date类对象的私有数据。
#include <iostream>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
/*编写一个程序,输出年月日时分秒。使得程序中的display函数作为类外的普通函数,
并在Time类和Date类中将display声明为友元函数。在主函数中调用display函数,
display函数分别引用Time类和Date类对象的私有数据。*/
class Time
{
public:
Time(int,int,int);
friend void display(Time &);
private:
int hour;
int minute;
int sec;
};
class Date
{
public:
Date(int,int,int);
friend void display(Date &);
private:
int month;
int day;
int year;
};
Time::Time(int h,int m,int s):hour(h),minute(m),sec(s){}
Date::Date(int m,int d,int y):month(m),day(d),year(y){}
void display(Time &t)
{
cout<<t.hour<<":"<<t.minute<<":"<<t.sec<<endl;
}
void display(Date &d)
{
cout<<d.month<<"/"<<d.day<<"/"<<d.year<<endl;
}
int main()
{
Time t1(22,02,10);
display(t1);
Date d1(11,20,2021);
display(d1);
return 0;
}
运行结果如下:
22:2:10
11/20/2021
--------------------------------
Process exited after 1.16 seconds with return value 0
请按任意键继续. . .
①友元关系不能继承
②如果类 A 被说明成类 B 的友元,类 B 不一定是类 A 的友元。
③友元函数不是类的成员函数。
④友元函数在类中声明。
友元函数详解
5445

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



