Click here to Skip to main content
15,894,540 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C++
#include <iostream.h>
#include <conio.h>
class oo{
     int l; public:
     oo():l(9){} 
      void operator +(int j)
      { 
l=l+j;
           }
      oo operator +(oo k)
      {  l+=k.l;
          return oo;
           }
   void d(){ cout &lt;&lt; l;}
      };

main()
{
oo s;
s+5; // working fine
s.d(); // working fine
5+s; // nolw i  want to do it ?<b></b>
s.d();
getch();
}<
Posted
Updated 17-Mar-15 1:50am
v2
Comments
Sergey Alexandrovich Kryukov 23-Feb-15 10:27am    
Just look at your code. First two lines are
#include
#include.

Please format it properly. Use "pre" tags.

All right, I've just done it for you, but click "Improve question" to see how it should be done, and do it correctly next time.

—SA

In order to have the compiler resolve the expression
C++
5 + s;

you have to provide a way to convert the object s into an int. That can be done by overloading
C++
int operator()()

that is the cast operator. Follow Sergey's links and you will learn how to do that.
 
Share this answer
 
Comments
CPallini 23-Feb-15 15:41pm    
5.
Stefan_Lang 24-Feb-15 3:44am    
This would work, but introducing cast operators can be dangerous. While the code above already has more serious issues than that, I'd prefer declaring an additional operator+ outside the class. See my solution.
Declare the required operator outside your class, like this:
C++
int operator+(int i, oo& o) {
   return o+i;
}

P.S.: I would have declared that second argument as const, but that would require your existing operator declarations to be const correct. It would also help if your operator implementations were consistent with expectations, i. e. they shouldn't modify the underlying object, unless you're overriding operator+=().
 
Share this answer
 
v3
Comments
nv3 24-Feb-15 5:53am    
Good points, Stefan.
 
Share this answer
 
Comments
CPallini 23-Feb-15 15:41pm    
5.
Sergey Alexandrovich Kryukov 23-Feb-15 15:49pm    
Thank you, Carlo.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900