addition of int to object member

Hi -

This is sort of a follow-on to an earlier thread, but I think it's different enough to merit a separate thread.

I have a class:

1
2
3
class reg {
   int c, n, ns;
<lots of other stuff>


I would like to be able to support this:

1
2
3
reg x, y;

y = x + 2;


With the resultant operation of y.ns = x.ns + 2;

What's the best way to do this? Thanks...I hope I made the explanation clear.
It's hard to think of what operator+ does for types other than numbers (mathematical addition) or strings (concatenation). I would therefore not use operator+ for your case. Instead create a member (or friend, or whatever) with a different name.

1
2
3
4
class reg {
   public:
       reg operator+( int rhs ) const;
};


or

1
2
3
4
// Note: Need friendship since you have to access private members of reg
reg operator+( const reg& lhs, int rhs )
{
}
Again I really think you are misusing/abusing operator overloading.

Operator overloading is there to make code more intuitive. This doesn't seem like it would accomplish that.


Just use a normal function for this. No need to overload the + operator.
Topic archived. No new replies allowed.