3

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 } 
3
  • 1
    Could you remove the line numbers? It prevents people from compiling your example. Good example code though! Commented Dec 18, 2012 at 6:38
  • Should mydata( int x = 0 )-constructor do mx = x; ? Commented Dec 18, 2012 at 6:40
  • #include<iostream.h>? Are you using turbo c++? Commented Dec 18, 2012 at 6:42

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I can only approve of removing the cast operators :6
2

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

Comments

1

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); } 

Comments

0

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).

3 Comments

That is what was suggested in the answer by @juanchopanza with bare minimum code sample
Yeah, I noticed. It was later edited, to add this point. The first I saw it wasn't there.
Thank you all for the response !

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.