Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ Operator overloading, [duplicate]

Whats wrong with my code shown below? please somebody throw some light. Thanks for your time !

    #include<iostream.h>
      using namespace std;

     struct mydata{
        int mx;
        mydata(int x = 0){}
        mydata operator+(const mydata& rhs){

                mydata temp(rhs);
                return temp;
        }
        operator int() const{ return mx; }
        operator double() const{ return mx; }
};


int main(){
        mydata d;
        mydata r = d + 5; // L1
        5 + d; // L2
        d + d; // L3
}
like image 735
sree Avatar asked Apr 21 '26 17:04

sree


1 Answers

First, you haven't stated what the problem is, but presumably you want an operator+ that sums the mx values of two mydata objects:

mydata operator+(const mydata& rhs){
        return mydata (mx + rhs.mx);
}

Next, I would suggest making this a non-member function, so that the LHS and RHS get treated in the same way, fixing the problem in L2:

mydata operator+(const mydata& lhs, const mydata& rhs){
        return mydata (lhs.mx + rhs.mx);
}

Finally, you will have an ambiguous overload remaining, because the compiler cannot decide whether to use the built-in operator+(int,int) or your own operator+(const mydata&, const mydata&). You can fix this by removing the cast operators int() and double().

See demo here.

like image 170
juanchopanza Avatar answered Apr 23 '26 06:04

juanchopanza