类的友元函数 (friend) 是定义在类外部, 但是有权限访问类的所有私有 (private) 成员和保护 (protected) 成员.
我们先来复习一下公有成员和私有成员的概念:
友元 (friend) 可以访问与其有好友关系的类中的私有成员 (有限制的共享).
友元包括友元函数和友元类:
Time 类:
#ifndef PROJECT2_TIME_H #define PROJECT2_TIME_H class Time { private: int hour; int minute; int second; public: Time(); Time(int, int, int); friend void display(Time &); // display是Time类的friend函数 }; #endif //PROJECT2_TIME_H
Time.cpp:
#include <iostream> #include "Time.h" using namespace std; Time::Time() : hour(0), minute(0), second(0) {} Time::Time(int h, int m, int s) : hour(h), minute(m), second(s) {} void display(Time &t) { // display不是Time类的成员函数, 但是可以引用Time中的私有成员 cout << t.hour << ":" << t.minute << ":" << t.second << endl; }
main:
#include "Time.h" #include <iostream> using namespace std; int main() { Time t1(8, 8, 8); display(t1); return 0; }
Time 类:
#ifndef PROJECT2_TIME_H #define PROJECT2_TIME_H class Date; // 对Date类进行提前引用声明 class Time { private: int hour; int minute; int second; public: Time(); Time(int, int, int); void display(Date &d); }; #endif //PROJECT2_TIME_H
Date 类:
#ifndef PROJECT2_DATE_H #define PROJECT2_DATE_H #include "Time.h" class Date { private: int year, month, day; public: Date(int, int, int); friend void Time::display(Date &d); }; #endif //PROJECT2_DATE_H
Time.cpp:
#include <iostream> #include "Time.h" #include "Date.h" using namespace std; Time::Time() : hour(0), minute(0), second(0) {} Time::Time(int h, int m, int s) : hour(h), minute(m), second(s) {} void Time::display(Date &d) { cout << d.year << "年" << d.month << "月" << d.day << "日" <<endl; cout << hour << ":" << minute << ":" << second << endl; }
main:
#include "Time.h" #include "Date.h" #include <iostream> using namespace std; int main() { Time t1(8, 8, 8); Date d1(2021, 5, 6); t1.display(d1); return 0; }
输出结果:
2021年5月6日
8:8:8
我们可以发现 display 不是 Date 类的成员函数, 但是可以引用 Date 中的私有成员.
Time 类:
#ifndef PROJECT2_TIME_H #define PROJECT2_TIME_H class Date; // 对Date类进行提前引用声明 class Time { private: int hour; int minute; int second; public: Time(); Time(int, int, int); void display(Date &d); }; #endif //PROJECT2_TIME_H
Date 类:
#ifndef PROJECT2_DATE_H #define PROJECT2_DATE_H #include "Time.h" class Date { private: int year, month, day; public: Date(int, int, int); friend class Time; // 友元类 }; #endif //PROJECT2_DATE_H
友元的性质:
友元的优缺点:
我们在使用友元的时候, 应当时刻考虑友元的缺点. 如果能用公共成员函数解决就不必用友元.