友元
类的友元函数是定义在类外部,但有权访问类的所有私有(private)成员和保护(protected)成员。尽管友元函数的原型有在类的定义中出现过,但是友元函数并不是成员函数。
注意
- 友元函数并不是成员函数
- 友元函数没有
this指针
1.全局友元函数
如果要声明函数为一个类的友元,需要在类定义中该函数原型前使用关键字 friend,如下所示:
C++
#include <iostream>
using namespace std;
class Box
{
double width;
public:
friend void printWidth(Box box) {
cout << "Width of box : " << box.width << endl;
}
void setWidth(double wid) {
width = wid;
}
};
// 程序的主函数
int main()
{
Box box;
// 使用成员函数设置宽度
box.setWidth(10.0);
// 使用友元函数输出宽度
printWidth(box);
return 0;
}TIP
因为友元函数并不是成员函数,所以在类外定义友元函数是和成员函数有区别的
c++
class Box
{
double width;
public:
friend void printWidth(Box box);
void setWidth(double wid);
};
void printWidth(Box box) {
cout << "Width of box : " << box.width << endl;
}
void Box::setWidth(double wid) {
width = wid;
}2.成员友元函数
若A类中的成员函数想访问B类中的私有属性,可以在B类中将A类中的函数设置为成员友元函数
c++
#include <iostream>
using namespace std;
class Home;
class GoodGriend {
public:
Home *home;
void visitBedRoom();
};
class Home {
friend void GoodGriend::visitBedRoom();
private:
string bedRoom = "卧室";
};
void GoodGriend::visitBedRoom() {
cout << home->bedRoom << endl;
}
// 程序的主函数
int main()
{
Home* home = new Home();
GoodGriend* goodfriend = new GoodGriend();
goodfriend->home = home;
goodfriend->visitBedRoom();
return 0;
}3.友元类
当A类是B类的由友元类时,A中所有的成员函数都可以访问B类中的私有成员
c++
#include <iostream>
using namespace std;
class Home;
class GoodGriend {
public:
Home *home;
void visitBedRoom();
};
class Home {
friend class GoodGriend;
private:
string bedRoom = "卧室";
};
void GoodGriend::visitBedRoom() {
cout << home->bedRoom << endl;
}
// 程序的主函数
int main()
{
Home* home = new Home();
GoodGriend* goodfriend = new GoodGriend();
goodfriend->home = home;
goodfriend->visitBedRoom();
return 0;
}