1

Is there a way to overload operator/() to use the class as the denominator?

Like so: int foo = 5 / object;

Dasaru
  • 2,828
  • 5
  • 25
  • 25
  • 2
    This excellent SO post on [operator overloading](http://stackoverflow.com/questions/4421706/operator-overloading) includes good information about implementing binary arithmetic operators. – Blastfurnace Jul 21 '12 at 02:33

3 Answers3

4

Use a free function:

int operator/ (const int, const MyClass &);

If it needs to access private members that you have no interface for, make it a friend inside your class as well:

friend int operator/ (const int, const MyClass &);
chris
  • 60,560
  • 13
  • 143
  • 205
  • What exactly is a free function? I've never heard of it before. – Dasaru Jul 21 '12 at 02:36
  • @Dasaru, One that's not enclosed in a class. In this case, it being a member function constrains it to take a `MyClass *` as the first argument, leaving one open. The order of arguments corresponds to the way you call it, so it's impossible to switch them if it's in the class. – chris Jul 21 '12 at 02:36
  • @Dasaru: You'll also see them called `non-member` functions. – Blastfurnace Jul 21 '12 at 02:37
3

Use a free function instead of a member function for operator/.

Binary operators typically have the same operand types. Assuming that foo has a non-explicit constructor taking an int, you would have:

struct foo
{
  foo(int i) {};
};

int operator/(foo const& x, foo const& y);
mavam
  • 12,242
  • 10
  • 53
  • 87
0

Free function is your friend:

int operator/ (int, const MyClass &);
iTayb
  • 12,373
  • 24
  • 81
  • 135