-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

2 Answers2

0
#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_an_ai Sep 19 '18 at 11:12
0

Try to use constructor correctly. For example:

#include <iostream>

using namespace std;

class Example
{
public:
    int x;
    Example(int a)
    {
        x=a;
    }
    Example operator+(Example obj)
    {
        Example ans(0);
        ans=x+obj.x;
        return ans;
    }
};

int main()
{
    Example a(10),b(20);
    Example ans=a+b;
    cout<<ans.x<<endl;
    return 0;
}
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the [help center](https://stackoverflow.com/help/how-to-answer). – Nol4635 Jul 25 '22 at 22:14