Examples of friend function by using C++

friend function with two classes
#include <iostream. h>
class B;     // forward declaration
class A {
    private:
      int data;
    public:
      A(): data(12){ }
      friend int func(A , B);   //friend function Declaration
};
class B {
    private:
       int data;
    public:
       B(): data(1){ }
       friend int func(A , B);  //friend function Declaration
};
int func(A d1,B d2)
/*Function func() is the friend function of both classes A and B. So, the private data of both class can be accessed from this function.*/
{
   return (d1.data+d2.data);
}
int main()
    {
        A a;
        B b;
        cout<<"Data: "<<func(a,b);
        return 0;
    }
/* C++ program to demonstrate the working of friend function.*/
#include <iostream. h>
class Distance
{
    private:
        int meter;
    public:
        Distance(){ }
        friend int func(Distance);  //friend function
};
int func(Distance d)            //function definition
{
    d.meter=5;         //accessing private data from non-member function
    return d.meter;
}
int main()
{
    Distance D;
    cout<<"Distace: "<<func(D);
    return 0;
}
// friend functions
#include <iostream. h>
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;
}
ادعو لوالدتي جزاكم الله خيرا
HamedDiyala
Examples of friend function by using C++ Reviewed by حامد طالب العراقي on 5/16/2015 10:06:00 ص Rating: 5

ليست هناك تعليقات:

نموذج الاتصال

الاسم

بريد إلكتروني *

رسالة *

يتم التشغيل بواسطة Blogger.