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.
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:
According to Tutorialspoint
Previous article: Copy constructor in C ++
Next lesson: Inline function in C ++
You should read it
- How to cancel your Facebook batch with Friend Remover Pro
- The meaning of Friend Emoji on Snapchat
- How to hide the Friend Activity tab on Spotify
- How to cancel a friend request Zalo has sent
- How to Deal when Your Best Friend Is Gay
- How to make a cute sedge hat shape for your friend on October 20
- Save time with these text formatting functions in Microsoft Excel
- How to Block All Friend Requests on Facebook
- How to cancel a friend invitation on Facebook in the fastest way
- Function in programming C
- DAY function in SQL Server
- MIN function in SQL Server
Maybe you are interested
iPhone XS Max and 6s Plus officially become 'classic' devices
How to decorate a beautiful 20/11 board for the classroom, 20/11 board decoration sample
Some classic Fallout games are free on the Epic Games Store
The 5 best apps and websites to watch classic movies
4 classic Linux tools that have better modern alternatives
Restore classic File Explorer with ribbon in Windows 11