C + + friend function and friend class

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.