C Friend-Friend
Friend is used to break the limit of protected or private protection, the first thing to do is to be declared in the class of the visitor is a friend function or friend class. The code is as follows
- #include <iostream>
- using namespace Std;
- Class Square{
- Private:
- int side;
- Public:
- Square(int a): Side(a){}
- Friend class Rectangle ; //declare the Class is friend
- };
- Class Rectangle {
- Private:
- int width, height;
- Public:
- rectangle< Span style= "color: #0000cc;" > (int aint B) :width (A) ,height (B{
- void Set_values (int a, int b){
- Width = a;
- Height = b;
- }
- int Girth();
- Friend int area (Rectangle &); //declare the friend function here
- int get_width(){return width;}
- int get_height(){return height;}
- void Conver_from_square(square &s){
- Width = Height = s. Side; //access so easily
- }
- };
- //implement The function here , Access easily , too
- int area (Rectangle &r){return (r. Width * r. Height); }
- int r_area (Rectangle &r{return R.get_width (* R.get_height (;
- int Rectangle:: Girth(){return width + width + height + height; }
- int main () {
- Test_sizeof:
- cout << "Sizeof:square" << sizeof(Square)
- << ", \trectangle" << sizeof(Rectangle) << "\ n" ;
- Test_access:
- Rectangle R(2, 3);
- cout < < << area (R<< Span style= "color: #0000cc;" >< <.girth () << endl
- cout << "Onather Way:area" << R_area(R) << Endl;
- Rectangle R1(2, 3);
- Square s(5);
- R1. Conver_from_square(S);
- cout << "Rectangle convering from Square, girth is" << R1. Girth() < ; < Endl;
- return 0;
- }
Results
- Sizeof:square 4, Rectangle 8
- Area:6 girth:10
- Onather Way:area 6
- Rectangle convering from Square, girth is 20
Look at the function
if it is not a friend function or class, the access case, such as the R_area () function, allows the friend function to access the member directly. But there is a difference between the member function and the function girth ()
Look at size, the friend or friend function does not increase the size of the class, just declare it.
C Friend-Friend