user4444350
user4444350

Reputation:

how to overload unary / operator?

I am trying to overload unary /(division) operator. But it causes error. However, when I try to overload +,-,* operators, it works fine. Problem causes oly for / operator. My code is as follows:

#include<bits/stdc++.h>
using namespace std;

class Box
{

     int x,y;
  public:
       void GetData(int a,int b)
        {
              x=a;y=b;
        }
       void Display()
       {
          cout<<x<<" "<<y;  
       }
      void operator /();
};

void Box::operator /()
{

    x/=2;
    y/=2;
}

int main()
{
     Box b;
     b.GetData(10,20);
    // I am getting error in the following line.
     /b;
     b.Display();
  return 0;
}

Upvotes: 1

Views: 470

Answers (1)

Joseph Mansfield
Joseph Mansfield

Reputation: 110738

There is no such thing as the unary / operator. The / operator takes two operands.

Note that just because two operators use the same symbol, doesn't mean they represent the same operation. Binary (as in an arity of 2) - is subtraction, while unary - is negation. Binary * is multiplication, while unary * is indirection. So while binary / is division, unary / is meaningless.

Upvotes: 5

Related Questions