Recently these days in the re-design mode GOF23, accidentally think of friends, do not use all quickly forget
Today to revisit the C + + friend knowledge, after learning almost no how to use, almost all with the design pattern of dealing with.
Although friends can improve efficiency, express clearly, but destroy the packaging mechanism of the class, so generally do not recommend the use of friends,
Friend Class Simple Demo:
Class A, want to expose private members to class Bclass A{friend class b;//set B to friend class public:a (int i): m_i (i) {}private:int m_i;int getInt () {return 100;}};/ /class B, want to access the private member of Class A, Class B{public:b (a A): M_a (a), M_n (a.m_i) {}void setint () {m_n = m_a.m_i;} Access private variable int getInt () {return m_a.getint ();};/ /Access Private function Private:int m_n; A m_a;}; void Main () {a A (8); b b (a); int n = B.getint ();}
The simple example is to declare in Class A that class A is a friend of Class B, so that Class B has access to the private members of Class A, but class A still cannot access the private members of Class B, remember.
Friend function Wood has this pointer, that is, in fact, it is an outside function, its declaration in the private or public segments and no difference, the friend function can not be inherited, like the father's friends may not be the son's friend.
Disclaimer: Friend + common function declaration
Implementation location: Can be outside the class or in a class
Implementation code: Same as normal function
Call: Similar to normal function, call directly
The friend function uses the following demo:
Class Ctest{friend void Print (const ctest& test);}; void print (const ctest& test) {cout<< "Print" <<ENDL;} void Main () {ctest test; Print (test);}
C + + friend function and friend class