0

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

Cœur
  • 37,241
  • 25
  • 195
  • 267
FreelanceConsultant
  • 13,167
  • 27
  • 115
  • 225
  • http://stackoverflow.com/questions/4421706/operator-overloading :) – melak47 Sep 02 '13 at 23:04
  • @melak47 Thanks, that also provides a lot of useful info, but not specifically about the unary `operator-`, still thanks anyway I will be using that in a minute! (Turns out I guessed correctly anyhow) (: – FreelanceConsultant Sep 02 '13 at 23:08

1 Answers1

1

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:

inline cents operator-(cents const& value)
{
    return cents(-value.m_cents);
}

Of course, the signature of the friend declaration needs to match the definition.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
  • @EdwardBird: so what's your question then...? – Dietmar Kühl Sep 02 '13 at 23:06
  • Asking to confirm if I was correct in my guess. I suspected I had missed something, but looks like I got it right first (second) time? Often it is as well to ask a question if unsure. Question hasn't been asked before as far as the search results could tell me. – FreelanceConsultant Sep 02 '13 at 23:09
  • @EdwardBird: OK, fair enough. BTW, just for the fun of it: you can also define unary plus: `inline cents operator+(cents value) { return value; }` It is rarely particular useful but for completeness... – Dietmar Kühl Sep 02 '13 at 23:13
  • Yeah good idea - seems like a good idea to implement both. I assume without the `operator+`, the compiler will complain if I tried to do something like: `cents c1(10); cents c2(12); c1 = +c2` ? – FreelanceConsultant Sep 02 '13 at 23:15
  • @EdwardBird: yes, this is correct. However, it is rare that expressions like this are used. – Dietmar Kühl Sep 02 '13 at 23:18