友元函數(shù)分為友元全局函數(shù)和友元成員函數(shù)
先看友元全局函數(shù):
定義一個Time類
#ifndef TIME_H
#define TIME_H
class Time
{
public:
Time(int h, int m, int s)
{
m_iHour = h;
m_iMinute = m;
m_iSecond = s;
}
private:
int m_iHour;
int m_iMinute;
int m_iSecond;
};
#endif // !TIME_H
在main函數(shù)中煞抬,定義一個打印時間的函數(shù)printTime()激率,由于Time中的數(shù)據(jù)成員被限制為私有角雷,因此全局函數(shù)是不能訪問的。
#include "time.h"
#include <iostream>
using namespace std;
void printTime(Time &t);
int main()
{
Time t(6, 34, 25);
printTime(t);
system("pause");
return 0;
}
void printTime(Time &t)
{
cout << t.m_iHour << ":" << t.m_iMinute << ":" << t.m_iSecond << endl;
}
此時編譯會出錯。
因此友元函數(shù)要出場了矩动,為了能訪問Time類中的私有數(shù)據(jù)成員,需要在Time類中聲明一個友元全局函數(shù)释漆,如下:
#ifndef TIME_H
#define TIME_H
class Time
{
friend void printTime(Time &t);
public:
Time(int h, int m, int s)
{
m_iHour = h;
m_iMinute = m;
m_iSecond = s;
}
private:
int m_iHour;
int m_iMinute;
int m_iSecond;
};
#endif // !TIME_H
如此悲没,編譯就能通過了!男图!
接下實現(xiàn)一個友元成員函數(shù)示姿。友元成員函數(shù)要求有兩個類才能實現(xiàn),因此再定義一個Match類