C + + Development Series-friend function friend class

Source: Internet
Author: User

Friend function

The private properties of a default class can only be accessed directly within the class.友元函数申明在内的内部,实现在类的外部可以直接访问类的私有属性。

classa1{ Public: A1 () {a1 = -; A2 = $; }intGetA1 () {return  This->a1; }//Declare a friend function    friend voidSetA1 (A1 *p,intA1);//This function is a good friend of this class    protected:Private:intA1;intA2;};voidSetA1 (A1 *p,intA1) {p->a1 = A1;}voidMain () {A1 mya1;     Cout<<mya1.geta1 () <<endl; SetA1 (&AMP;MYA1, -);//Modify private properties of Class A with friend functionCout<<mya1.geta1 () <<endl; System"Pause");}

Add:

    • The Friend function declaration statement location is independent of private and public.
    • A friend function typically has parameters for that object, access private member property data through an object parameter
Friend class
    • If Class B is a friend class of Class A, all member functions of Class B are friend functions of Class A
    • A friend class is typically designed as an auxiliary class for passing messages between data operations or classes

C + + Development Series-friend function 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.