C + + friend function

Source: Internet
Author: User
Tags function definition

1, why to introduce friend function: reduce system overhead and increase efficiency when data sharing between classes is implemented

C + + use friend modifier, you can let some of the functions you set to operate on these protection data, avoid the class members all set to public, to maximize the security of data members.

Specifically: to enable member functions of other classes to access private variables of the class directly

That is: Allow outside classes or functions to access the class's private and protection variables, so that two classes share the same function ( friend function is not a member of the class function, is a normal function )

Advantages: Can improve efficiency, express simple, clear

Disadvantage: The friend function breaks the encapsulation mechanism , uses the member function as far as possible, unless the unavoidable case makes the UF meta-function.

2. When to use friend function:

1) operator overloading requires the use of friends for some occasions.

2) two classes to share the data

3. How to use friend function:

Arguments to the friend function:

because the friend function does not have this pointer , there are three conditions for the parameter :

1, to access non-static members, the object is required to do parameters;--common (friend function often contains parameters)

2. When you want to access a static member or global variable, you do not need the object to do the argument

3, if the object that makes the parameter is a global object, then the object does not need to do parameters

The location of the friend function:

Because a friend function is a function outside the class, its declaration can be placed in the private or public segment of the class without distinction.

Call of the friend function:

You can directly adjust the cell function, do not need to pass through the object or pointer


friend function :
A friend function is a non-member function that can directly access a private member of a class. It is a normal function that is defined outside the class, it does not belong to any class, but it needs to be declared in the definition of the class, simply by adding a keyword friend to the name of the friend, in the following format:
Friend type function name (formal parameter);

The declaration of a friend function can be placed either in the private part of the class or in the public part, which is no different, and is a friend function of the class.
A function can be a friend function of more than one class, and it needs to be declared separately in each class.
The call of the friend function is consistent with the method and principle of calling the general function.

Friend class :
All member functions of a friend class are friend functions of another class and can access hidden information in another class, including private members and protected members.
When you want a class to be able to access the private members of another class, you can declare the class as a friend of another class. The statement format that defines the friend class is as follows:
Friend class name;
Where:friend and class are keywords, and the class name must be a class that has already been defined in the program.

Depending on the source of this function, there are three ways to do this:

1, Common function friend function:

A) Purpose: to enable ordinary functions to access the friend of the class

b) Syntax: Declaration location: Public private, often written as public

Disclaimer: Friend + common function declaration

Implementation location: Can be outside the class or in a class

Implementation code: Same as normal function (no friend and class::)

Call: Similar to normal function, call directly

c) Code:

classinteger{Private:    intnum; Public: FriendvoidPrint (Constinteger& obj);//declaring friend functions};voidPrint (Constinteger& obj)// do not use friend and class:: {    //function Body}voidMain () {INTEGER obj; Print (obj);//Call directly}

2. all member functions of Class Y are class X friend functions - friend class

A) Purpose: Use a single declaration to make all functions of the Y Class A friend of Class X

It provides a way to collaborate between classes so that objects of class Y can have the functions of Class X and Class Y

Specifically:

Premise: A is a friend of B (= "A" member function can access all members in B, including private members and public members--old forgetting)

Then: In a, with class B, you can use ~b directly. Private variable ~ form access to private variable

b) Syntax: Declaration location: Public private can, often write as private (the class as a variable)

Disclaimer: Friend + class name---not an object.

Call:

c) Code:

#include <iostream>using namespacestd;classgirl{Private:    Char*name; intAge ; FriendclassBoy//declaration class boy is a friend of class girl Public: Girl (Char*n,intAge ): Name (n), age {};}; classboy{Private:    Char*name; intAge ;  Public: Boy (Char*n,intAge ): Name (n), age {}; voidDisp (Girl &);  }; voidBoy::d ISP (Girl &x) //The function must be defined after the Girl class definition, otherwise the private variable in the girl class is still unknown {cout<<"Boy's name is:"<<name<<", Age:"<<age<<Endl; cout<<"Girl ' s name is:"<<x.name<<", Age:"<<x.age<<Endl; //with the help of friends, in the boy's member function disp, with the help of Girl object, direct access to girl's private variables//under normal circumstances, only the private variables of girl are allowed in the member functions of Girl}  voidMain () {Boy B ("AAA",8); Girl g ("BBB", About); B.disp (g); }

3. A member function of Class Y is a friend function of class X

A) Objective: to make a member function of Class y a friend of class X

In particular: In this member function of Class Y, with the help of parameter x, you can use X directly. Private variables in the form of access to private variables

b) Syntax: Declaration location: Declared in public (itself as a function)

Declaration: Friend + Declaration of member function

Call: Define Y's Object y---use y to call your own member function---Use the friend mechanism in your own member function

c) Code:

classgirl;classboy{Private:    Char*name; intAge ;  Public: Boy (); voidDisp (Girl &);    }; classgirl{Private:    Char*name; intAge ;  Public: Girl (Char*n,intA); FriendvoidBoy::d ISP (Girl &);//declaring a member of the Class boy function disp () is a friend function of class girl}; voidBoy::d ISP (Girl &x) {cout<<"Boy's name is:"<<name<<", Age:"<<age<<endl;//Access your Own (boy) object members and access your own private variables directlycout<<"Girl ' s name is:"<<x.name<<", Age:"<<x.age<<Endl; //with the help of friends, in the boy's member function disp, with the help of Girl object, direct access to girl's private variables//under normal circumstances, only the private variables of girl are allowed in the member functions of Girl}  voidMain () {boy B ();      Girl g ();  B.disp (g); }

4. Use friend operator<< (overload of << operator) in template class

A) How to use:

Declare in the template class:

operator<< <> (ostream& cout,const mgraph<vextype,arctype>& G);  

Defined in the template class:

template<class Vextype,class arctype>ostreamoperator<< (ostream & cout,const mgraph<vextype,arctype>& G) {    // function definition }

b) Note:

To declare a function as a non-template function:

operator<< (ostream& cout,const mgraph& G);  

To declare a function as a template function:

operator<< <> (ostream& cout,const mgraph<vextype,arctype>& G);  

Or:

operator<< <VexType,ArcType> (ostream& cout,const mgraph<vextype,arctype> & G);  

Description
Add operator<< <> to the function declaration: The operator<< function is defined as a function template, and the function template is declared as a friend of the class template.
The actual declaration function: Here the template parameters can be omitted, but the angle brackets can not be omitted

operator<< <VexType,ArcType> (ostream& cout,const mgraph<vextype,arctype> & G);  

5. The difference between a friend function and a member function of a class: The member function has this pointer, and the friend function does not have the this pointer.

Note When using friend classes:
(1) A friend relationship cannot be inherited.
(2) friend relationship is one-way and not commutative. If Class B is a friend of Class A, class A is not necessarily a friend of Class B, it depends on whether there is a corresponding declaration in the class.
(3) friend relationship does not have transitive nature. If Class B is a friend of Class A, Class C is a friend of B, Class C is not necessarily a friend of Class A, but also to see if there is a corresponding declaration in the class

C + + friend function

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.