2

Let's say I have a class Number

class Number
{
public:
    int numb;

    Number (int g)
    {
        numb = g;
    }

    int operator+(int h)
    {
        return this->numb+h;
    }
};

And when I try to use my overloaded operator

cout << 3 + s; // doesn't work
cout << s + 3;

I understand why it doesn't work, but I don't know how to make it work for 3 + s

Of course, I can write operator+ with 2 arguments outside the class, but I want to have my operator overloaded in the class.

I've googled it, but didn't find any solution.

Aleksander Monk
  • 2,787
  • 2
  • 18
  • 31

3 Answers3

1

Easiest way to go: write another overload outside of your class

class Number
{
public:
    int numb;

    Number (int g)
    {
        numb = g;
    }

    int operator+(int h)
    {
        return this->numb+h;
    }
};

int operator+(int h, Number& n)
{
    return n.numb+h;
}

int main()
{
    int s = 42;
    std::cout << 3 + s;
    std::cout << s + 3;
}

Live Example

This also works if your data is private (but make sure the outside function has access to those members)

class Number
{
    int numb;

public:
    Number (int g)
    {
        numb = g;
    }

    int operator+(int h)
    {
        return this->numb+h;
    }

    friend int operator+(int, Number&);
};

int operator+(int h, Number& n)
{
    return n.numb+h;
}
Marco A.
  • 43,032
  • 26
  • 132
  • 246
  • Your friends are not always exposed in public, and doing friendships may not be the best way to go. – g24l Oct 17 '15 at 11:15
1

Of course, I can write operator+ with 2 arguments outside the class, but I want to have my operator overloaded in the class.

This is like saying "Of course I could hammer in my nail with a hammer, but I want to use a screwdriver..."

Some other solutions suggested using both a member and a non-member, but that is redundant: if you add the non-member then you no longer need the member!

The proper way to overload operator+ is to use the non-member:

Number operator+(Number a, Number b)
{
    return a.numb + b.numb;
}

Another way to write this is to use operator+= as a helper (then your class will support += too):

Number operator+(Number a, Number b)
{
    return a += b;
}

with member function:

Number &operator+=(Number b)
{
    numb += b.numb;
    return *this;
}

You could either make operator+ return Number or int, your choice.

Community
  • 1
  • 1
M.M
  • 138,810
  • 21
  • 208
  • 365
0

Just write an operator outside the class that calls the one in your class!

template<typename T> T operator+(T a, Number& n)
{
  return n+a;
}
g24l
  • 3,055
  • 15
  • 28