1.友元
C++ 中可以使用 friend 关键字将函数、声明为某个类的友元
友元具有一些特权,可以访问 private 的成员
友元只能授予,不能索取,单向,不能传递
2. 友元函数
在类体重使用 friend 关键字进行声明
friend void fun(); // func 是非成员函数,不属于任何类
#ifndef TIME_H
#define TIME_H
class CTime{
public:
// 构造函数
CTime();
// 带参数构造函数
CTime(int hour);
// 析构函数
~CTime();
void setHour(int hour);
int getHour();
// 友元函数
friend void func();
private:
int m_nHour;
};
#endif
此时就可以调用其中的私有变量了
#include <iostream>
#include "Time.h"
using namespace std;
void func() {
CTime time(8);
// 通过友元,这里可以访问私有变量
time.m_nHour = 3;
}
int main() {
func();
return 0;
}
3. 友元类
在类体重使用 friend 关键字声明为自己的友元类
friend Object
- 头文件
#ifndef DATE_H
#define DATE_H
// 类的前置声明
class CTime;
class CDate {
public:
CDate(int year, int month, int day);
// 友元的应用
void display(const CTime& time);
private:
int m_nYear;
int m_nMonth;
int m_nDay;
};
#endif
- 对象文件
#include "Date.h"
#include "Time.h"
#include <iostream>
// 类的前置声明
class CTime;
using namespace std;
// 构造函数
CDate::CDate(int year, int month, int day)
// 初始化列表,进行参数初始化
:m_nYear(year),m_nMonth(month) ,m_nDay(day)
{
}
void CDate::display(const CTime& mCTime){
// 通过友元访问私有变量
cout<<m_nYear<<" - "<<m_nMonth<<" - "<<m_nDay<<""<<mCTime.m_nHour<<endl;
}
- 友元对象的声明
#ifndef TIME_H
#define TIME_H
// 类的前置声明
class CDate;
class CTime{
public:
// 构造函数
CTime();
// 带参数构造函数
CTime(int hour);
// 析构函数
~CTime();
void setHour(int hour);
int getHour();
// 友元函数
friend void func();
// 友元对象
friend CDate;
private:
int m_nHour;
};
#endif
4. 友元的缺点
面向对象的基本原则包括封装和信息的隐藏,而友元可以访问其他类的私有成员,这是对封装原则的破坏,开发时慎重选择。