Several answers now suggest using a non-member operator+
overload to allow "addition" of Distance
and int
objects. This doesn't really make sense: what does it mean to add a Distance
, which has a unit, to an int
, which does not?
However, it does make sense to add two Distance
objects together. If you have one distance of two feet and add another distance of three feet to it, you get a distance of five feet. This makes sense.
You can accomplish this by overloading operator+
between two Distance
objects (for simplicity, I've assumed that your Distance
only has a single field containing inches. In a real-world application, you wouldn't want to have separate fields for inches and feet. You'd probably want to use an SI unit, like meters, but that depends on the application and is entirely up to you):
Distance operator+(const Distance& lhs, const Distance& rhs)
{
return Distance(lhs.inches + rhs.inches);
}
This doesn't help you, though, if you want to be able to do something along the lines of
Distance d;
d = d + 42; // assume 42 has the same units as a Distance object has
In order to get this to make sense, you can use a converting constructor:
struct Distance
{
Distance(int in = 0) : inches(in) { }
private:
int inches;
};
The constructor here is a converting constructor because it is not explicit
and can be called with a single argument. It allows a single int
(or a value that is implicitly convertible to an int
) to be converted to a Distance
object. This allows you to write
Distance d;
d = d + 42;
Why is this different from using an operator+
overload that takes a Distance
and an int
argument? Simple: it forces the conversion from int
to Distance
to take place before the addition, so the actual addition doesn't have to care about its operands: it simply adds two distances together and lets the Distance
constructors deal with any conversions that need to take place.