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

前端 未结 30 2002
孤街浪徒
孤街浪徒 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:42

    You may use friendship when different classes (not inheriting one from the other) are using private or protected members of the other class.

    Typical use cases of friend functions are operations that are conducted between two different classes accessing private or protected members of both.

    from http://www.cplusplus.com/doc/tutorial/inheritance/ .

    You can see this example where non-member method accesses the private members of a class. This method has to be declared in this very class as a friend of the class.

    // friend functions
    #include 
    using namespace std;
    
    class Rectangle {
        int width, height;
      public:
        Rectangle() {}
        Rectangle (int x, int y) : width(x), height(y) {}
        int area() {return width * height;}
        friend Rectangle duplicate (const Rectangle&);
    };
    
    Rectangle duplicate (const Rectangle& param)
    {
      Rectangle res;
      res.width = param.width*2;
      res.height = param.height*2;
      return res;
    }
    
    int main () {
      Rectangle foo;
      Rectangle bar (2,3);
      foo = duplicate (bar);
      cout << foo.area() << '\n';
      return 0;
    }
    

提交回复
热议问题