1. 友元定义
类的友元函数是定义在类内部,但有权访问类的所有私有(private)成员和保护(protected)成员。尽管友元函数的原型有在类的定义中出现过,但是友元函数并不是成员函数。 友元可以是一个函数,该函数被称为友元函数;友元也可以是一个类,该类被称为友元类,在这种情况下,整个类及其所有成员都是友元。如果要声明函数为一个类的友元,需要在类定义中该函数原型前使用关键字 friend
2.友元函数
友元函数也无法调用原类的成员,而是调用对象成员值
#include<iostream>
using namespace std;
class Box
{
private:
int Lenght{ 1 };
int width{ 1 };
int height{ 1 };
public:
explicit Box(int x, int y, int z):Lenght { x }, width { y }, height { z }{} //三形参的构造函数
int getLenght() //函数调用私用成员
{
return Lenght;
}
int friend getwidth(Box box1) //友元函数调用私用成员
{
return box1.width;
}
};
int main()
{
Box box1{ 5,5,5 }; //显示调用
cout << box1.getLenght() << endl;//调用函数
cout << getwidth(box1) << endl; //待用友元函数
return 0;
}
3. 友元类
友元类也无法调用原类的成员,而是调用对象成员值
#include<iostream>
using namespace std;
class Box
{
private:
int Lenght{ 1 };
int width{ 1 };
int height{ 1 };
public:
explicit Box(int x, int y, int z):Lenght { x }, width { y }, height { z }{} //三形参的构造函数
int getLenght() //函数调用私用成员
{
return Lenght;
}
int friend getwidth(Box box1)
{
return box1.width;
}
friend class bigBox;
};
class bigBox
{
public:
int getheight(Box box1)
{
return box1.height;
}
};
int main()
{
Box box1{ 5,5,5 };
bigBox box2;
cout << box1.getLenght() << endl;//结果5
cout << getwidth(box1) << endl; //结果1
cout << box2.getheight(box1) << endl;
return 0;
}