有些情形下,需要允许类的非成员函数访问类的私有成员,同时阻止一般的访问。友元便是在这样的背景下引入。
友元可以是普通的非成员函数,或在该类之前定义的其他类的成员函数,或整个类。
#include<iostream>
using namespace std;
class B;
class A{
public:
int test(B b);
private:
int x;
};
class B{
friend class A;
public:
B(int i):value(i){}
private:
int value;
};
int A::test(B b){
return b.value;
}
int main(){
B b(5);
A a;
cout<<a.test(b);
return 0;
}