When should you use 'friend' in C++?

前端 未结 30 2084
孤街浪徒
孤街浪徒 2020-11-22 10:12

I have been reading through the C++ FAQ and was curious about the friend declaration. I personally have never used it, however I am interested in exploring the language.

30条回答
  •  眼角桃花
    2020-11-22 10:39

    In C++ "friend" keyword is useful in Operator overloading and Making Bridge.

    1.) Friend keyword in operator overloading :
    Example for operator overloading is: Let say we have a class "Point" that has two float variable
    "x"(for x-coordinate) and "y"(for y-coordinate). Now we have to overload "<<"(extraction operator) such that if we call "cout << pointobj" then it will print x and y coordinate (where pointobj is an object of class Point). To do this we have two option:

       1.Overload "operator <<()" function in "ostream" class.
       2.Overload "operator<<()" function in "Point" class.
    Now First option is not good because if we need to overload again this operator for some different class then we have to again make change in "ostream" class.
    That's why second is best option. Now compiler can call "operator <<()" function:

       1.Using ostream object cout.As: cout.operator<<(Pointobj) (form ostream class).
    2.Call without an object.As: operator<<(cout, Pointobj) (from Point class).

    Beacause we have implemented overloading in Point class. So to call this function without an object we have to add"friend" keyword because we can call a friend function without an object. Now function declaration will be As:
    "friend ostream &operator<<(ostream &cout, Point &pointobj);"

    2.) Friend keyword in making bridge :
    Suppose we have to make a function in which we have to access private member of two or more classes ( generally termed as "bridge" ) . How to do this:
    To access private member of a class it should be member of that class. Now to access private member of other class every class should declare that function as a friend function. For example : Suppose there are two class A and B. A function "funcBridge()" want to access private member of both classes. Then both class should declare "funcBridge()" as:
    friend return_type funcBridge(A &a_obj, B & b_obj);

    I think this would help to understand friend keyword.

提交回复
热议问题