注:轉載請標明原文出處鏈接:https://xiongyiming.blog.csdn.net/article/details/100747994
1 友元函數
函數定義在全局函數中,並且把這個函數聲明爲另外一個函數的友元函數,我們稱之爲友元全局函數。
函數定義在類中,並且把這個類聲明爲另外一個類的爲友元函數,我們稱之爲友元成員函數。
(1) 友元全局函數
(2) 友元成員函數
代碼示例
要求
友元函數
- 友元全局函數
- 友元成員函數
Time.h
#pragma once
#include<iostream>
#include"Match.h"
using namespace std;
class Time
{
friend void printTime(Time &t);//友元全局函數聲明
friend void Match::printTime(Time &t); //友元成員函數聲明
public:
Time(int hour, int min, int sec);
private:
int m_iHour;
int m_iMinute;
int m_iSecond;
};
Time.cpp
#include<iostream>
#include"Time.h"
using namespace std;
Time::Time(int hour, int min, int sec)
{
m_iHour = hour;
m_iMinute = min;
m_iSecond = sec;
}
Match.h
#pragma once
#include<iostream>
using namespace std;
class Time;
class Match
{
public:
void printTime(Time &t);
};
Match.cpp
#include<iostream>
#include"Match.h"
#include"Time.h"
using namespace std;
void Match::printTime(Time &t)
{
cout << t.m_iHour << ":" << t.m_iMinute << ":" << t.m_iSecond << endl;//需要聲明友元函數 才能訪問私有成員
}
main.cpp
#include<iostream>
#include"Time.h"
#include"Match.h"
using namespace std;
/******************
友元函數
1. 友元全局函數
2. 友元成員函數
********************/
//全局函數 聲明
void printTime(Time &t);
int main()
{
//友元全局函數
Time t1(7, 27, 25);
printTime(t1);
cout << endl;
cout << "-------------------" << endl;
cout << endl;
// 友元成員函數
Time t2(10, 00, 00);
Match m;
m.printTime(t2);
cin.get();
return 0;
}
//全局函數 定義
void printTime(Time &t)
{
cout << t.m_iHour <<":"<< t.m_iMinute << ":" << t.m_iSecond << endl;//需要聲明友元函數 才能訪問私有成員
}
運行結果
2 友元類
關於友元的注意事項
- 友元關係不可傳遞;
- 友元關係的單向性;
- 友元聲明的形式及數量不受限制;
- 友元只是封裝的補充.
代碼示例
Time.h
#pragma once
#include<iostream>
using namespace std;
class Match;
class Time
{
friend Match;//聲明友元類
public:
Time(int hour, int min, int sec);
private:
void printTime();
int m_iHour;
int m_iMinute;
int m_iSecond;
};
Time.cpp
#include<iostream>
#include"Time.h"
using namespace std;
Time::Time(int hour, int min, int sec)
{
m_iHour = hour;
m_iMinute = min;
m_iSecond = sec;
}
void Time::printTime()
{
cout << m_iHour << "時" << m_iMinute << "分" << m_iSecond <<"秒" << endl;
}
Match.h
#pragma once
#include<iostream>
#include"Time.h"
using namespace std;
class Match
{
public:
Match(int hour, int min, int sec);
void testTime();
private:
Time m_tTimer;
};
Match.cpp
#include<iostream>
#include"Match.h"
#include"Time.h"
using namespace std;
Match::Match(int hour, int min, int sec):m_tTimer(hour,min,sec)
{
}
void Match::testTime()
{
m_tTimer.printTime();
cout << m_tTimer.m_iHour << ":" << m_tTimer.m_iMinute << ":" << m_tTimer.m_iSecond << endl;
}
main.cpp
#include<iostream>
#include"Time.h"
#include"Match.h"
using namespace std;
/******************
友元類
********************/
int main()
{
Match m(10, 00, 00);
m.testTime();
cin.get();
return 0;
}
運行結果
參考資料
[1] C++遠征之模板篇