uss
uss

Reputation: 1309

c++ Operator overloading,

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
}

Upvotes: 3

Views: 231

Answers (4)

Necto
Necto

Reputation: 2654

The problem (stated the comment) is that compiler doesn't know which + you want to execute:

(double)d + 5

or

(int)d + 5

In order to resolve this ambiguoity, you should point the type conversion, or replace one of these operators by a named function:

    operator int() const{ return mx; }
    operator double() const{ return mx; }

If you want instead use d + mydata(5) you should write so, because the above variants are more likely to be applied

Upvotes: 2

billz
billz

Reputation: 45410

You could provide a few non-member operator+ to enable operator+ with different data type:

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

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

Upvotes: 1

juanchopanza
juanchopanza

Reputation: 227390

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.

Upvotes: 3

Manoj R
Manoj R

Reputation: 3247

You can't do 5 + d. 5 can not be converted to class object like this. For this you need to get the operator + definition out of the class method. (in my knowledge preferably friend).

Upvotes: 0

Related Questions