-2
#include<iostream>
using namespace std;
class money
{
    int rs;  
    int p; 

    public:

    void setdata (int x , int y) 

     {rs=x; p=y;}

    void show() 

   { cout  <<rs  <<"."  <<p; }  

    money operator += (int a)  {

    money temp;
    temp.rs=rs+a.rs;
    temp.p=p+a.p;   
    return (temp);  
    }
};



  int main() {

    money c1,c2;

    c1.setdata(8,2);

    c2=c1.operator+=(4);

    c2.show();

}

Can someone tell me why the operator += overloading doesn't work?

My desiring output is 12.2 but the output i got is 16.2 .

I am sending 4 as argument and i want this argument is added in r (ruppee) part

1 Answers1

1
#include<iostream>
using namespace std;
class money
{
    int rs;  
    int p; 

    public:

    void setdata (int x , int y) 

     {rs=x; p=y;}

    void show() 

   { cout  <<rs  <<"."  <<p; }  

   money& operator+=(int a) 
   { rs += a; return *this; }
};



  int main() {

    money c1,c2;

    c1.setdata(4,2);

     c2=c1+=(4);               //c2=c1.operator+=(4);

    c2.show();

}
  • `c2=c1+=(4);` is correct, but it completely misses the point of having a `operator+=` instead of a `operator+`. `operator+=` modifies the left hand side and its return can be assigned to `c2` but typically you dont. Just use `c1+=4; c1.show();` – 463035818_is_not_a_number Sep 19 '18 at 11:12