1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

operator overloading using friend function

Discussion in 'C++' started by techme, Mar 22, 2010.

  1. techme

    techme New Member

    Joined:
    Feb 15, 2010
    Messages:
    86
    Likes Received:
    0
    Trophy Points:
    0
    If i have a class:

    Code:
    class Rational{
    ..
    ..
    Rational operator+(Rational &rat);
    friend Rational operator+(Rational rat1, Rational rat2);
    ...
    ...
    };
    
    Rational operator+(Rational rat1, Rational rat2);
    
    int main()
    {
    Rational r1(2,3),r2(4,5);
    ....
    ...
    r1=r1+r2;
    ...
    }

    -------------------------------
    I know in this case the member function of class Rational will be invoked. But how do i invoke the non-member friend function which is in the global area. Am i supposed to do this:

    r1=operator+(r1,r2);

    ?
     
  2. creative

    creative New Member

    Joined:
    Feb 15, 2010
    Messages:
    87
    Likes Received:
    0
    Trophy Points:
    0
    Normally, you would have operator += as the member function
    (returning a reference), and operator + as the non member function
    (implemented in terms of the member +=). And no need for the non-member
    function to be a friend.

    Code:
    class Rational
    {
    public:
      Rational & operator += (const Rational & rat)
      {
       // code then
       return *this;
      }
    };
    
    Rational operator + (Rational rat1, const Rational & rat2)
    {
         return rat1+=rat2;
    }
    
    // or 
    Rational operator + (const Rational & rat1, const Rational & rat2)
    {
       Rational tmp = rat1;
       return tmp+=rat2;
    }
     

Share This Page