Friend Basic concept: 1, a general function is declared as a class of friend function 2, a Class A of some member functions declared as a Class B friend function 3, a Class A is declared a Class B friend class. The role of friends: You can access all member variables and member methods in class B, whether public,protected or private. 1, to declare a general function show as a friend function of a class
#include <iostream>using namespace std;class Test{ friend void show(const Test &t);public: Test(int d = 0) : data(d){}private: void fun()const{ cout << "fun:" << data << endl; } int data;};//友元,即可以访问私有成员变量,也可以访问私有方法 void show(const Test &t){ cout << "friend of Test:" << t.data << endl; t.fun();}int main(){ Test t(100); show(t); return 0;}
2, the fun member function of a Class A is declared as a friend function of class test, but the FUN1 function of Class A is not a friend function of class test, so the private member of test cannot be accessed in fun1.
#include <iostream>using namespace std;class Test;class A{ public: A(int d = 0) : data(d){} void fun(const Test &t); void fun1(const Test &t); private: int data;};class Test{ friend void A::fun(const Test &t);public: Test(int d = 10) : data(d){}private: int data;};void A::fun(const Test &t){ cout << t.data << endl;}void A::fun1(const Test &t){ //编译不能通过,因为fun1不是class Test的友元函数。 //cout << t.data <<endl; }int main(){ Test t(100); A a; a.fun(t);}
3, Class B is declared as a friend of class test, so all public member functions of Class B are friend functions of class test.
#include <iostream>using namespace std;class Test;class B{public: void fun1(const Test &t); void fun2(const Test &t);};class Test{ friend class B;public: Test(int d = 0) : data(d){}private: void pri()const{ cout << "pri" << endl; } int data;};void B::fun1(const Test &t){ cout << t.data << endl;}void B::fun2(const Test &t){ t.pri();}int main(){ Test t(10); B b; b.fun1(t); b.fun2(t);}
The basic concept of friend element in C + +