I am looking into implementing the unary 'negation', 'sign-inversion' or 'subtraction' operator, probably as a friend function to my class.
My guess at the correct way to do this is:
namespace LOTS_OF_MONNIES_OH_YEAH { // sorry, couldn’t resist using this namespace name
class cents
{
public:
cents(const int _init_cents)
: m_cents(_init_cents)
{
}
public:
friend inline cents operator-(const cents& _cents);
private:
int m_cents;
};
inline cents operator-(const cents& _cents)
{
return cents(-(_cents.m_cents));
}
}
Is my guess correct?
PS: Ideally namespace names should be in lower case as upper case is often used exclusively for constants, however I thought upper case provided more impact.
PPS: Ripped the example from here
The unary operator takes exactly one argument (hence the unary). If you want to implement it as non-member function you could define it like this:
Of course, the signature of the
friend
declaration needs to match the definition.