Friend function in C ++

The friend function in C ++ of a class is defined outside of that class scope, but it has access to all private and protected members of that class. Even if the prototypes for friend functions appear in the class definition, friend functions are not member functions.

The friend function in C ++ of a class is defined outside of that class scope, but it has access to all private and protected members of that class. Even if the prototypes for friend functions appear in the class definition, friend functions are not member functions.

A friend can be a function, a function pattern, or a member function, or a class or a class template, in this case, the entire class and all its members are friends.

To declare a function of friend function of a class, precede that function prototype in class definition with friend keyword in C ++, as follows:

 class Box { double chieurong ; public : double chieudai ; friend void inChieuRong ( Box box ); void setChieuRong ( double rong ); }; 

To declare all member functions of the LopMai class as friend type of LopMot class, put a following declaration in the definition of LopMot class:

 friend class LopHai ; 

You consider the following program:

 #include using namespace std ; class Box { double chieurong ; public : friend void inChieuRong ( Box box ); void setChieuRong ( double rong ); }; // phan dinh nghia ham thanh vien void Box :: setChieuRong ( double rong ) { chieurong = rong ; } // Ghi chu: inChieuRong() khong la ham thanh vien cua bat cu class nao. void inChieuRong ( Box box ) { /* Boi vi, ham inChieuRong() la ham friend cua Box, do vay no co the truc tiep truy cap bat cu thanh vien nao cua class nay */ cout << "Chieu rong cua box la: " << box . chieurong << endl ; } // ham main cua chuong trinh int main ( ) { Box box ; // thiet lap chieurong cua box, khong su dung ham thanh vien box . setChieuRong ( 25.3 ); // su dung ham friend de in chieu rong. inChieuRong ( box ); return 0 ; } 

Compiling and running the above C ++ program will produce the following results:

Picture 1 of Friend function in C ++

According to Tutorialspoint

Previous article: Copy constructor in C ++

Next lesson: Inline function in C ++

Update 25 May 2019
Category

System

Mac OS X

Hardware

Game

Tech info

Technology

Science

Life

Application

Electric

Program

Mobile