友元函数
When the function is declared as a friend, then it can access the private and protected data members of the class.
#include <iostream>
#include <string>
using namespace std;
class sample{
int length, breadth;
public:
sample(int length, int breadth):length(length),breadth(breadth)
{}
friend void calcArea(sample s); //friend function declaration
};
//friend function definition
void calcArea(sample s){
cout<<"Area = "<<s.length * s.breadth;
}
int main()
{
sample s(10,15);
calcArea(s);
return 0;
}
友元类
class A{
……
friend class B;
};
class B{
……..
};
As depicted above, class B is a friend of class A. So class B can access the private and protected members of class A.
But this does not mean that class A can access private and protected members of the class B. Note that the friendship is not mutual unless we make it so.
Similarly, the friendship of the class is not inherited. This means that as class B is a friend of class A, it will not be a friend of the subclasses of class A.
#include <iostream>
#include <string>
using namespace std;
class Area{
int length,breadth,area;
public:
Area(int length,int breadth):length(length),breadth(breadth)
{}
void calcArea(){
area = length * breadth;
}
friend class printClass;
};
class printClass{
public:
void printArea(Area a){
cout<<"Area = "<<a.area;
}
};
int main(){
Area a(10,15);
a.calcArea();
printClass p;
p.printArea(a);
return 0;
}
源自:https://www.softwaretestinghelp.com/friend-functions-in-cpp/