0

Hi. Could you please guide me in performing operator overloading of Unary operator? Just explain the method with an example. Please add the explanation.

4
Contributors
4
Replies
5
Views
7 Years
Discussion Span
Last Post by Fbody
0

You mean the + operator?

class MyClass
{
private:
   int x;
public:
   MyClass() {x = 0;}
   MyClass operator+(int x)
   {
      MyClass n = *this;
      n.x = n.x + x;
      return n;
   }
};

Edited by Ancient Dragon: n/a

0

Are you referring to the addition operator (operator+) or to any operator that takes only one operand?

There are 4 ways to overload operators, and which specific method you use depends on if it's a Unary operator or a Binary operator and whether it's a member function or not.

To overload a non-member Unary operator, the operand becomes a parameter to the operator function:

struct example {
  int anInt;
};

//Overload the Unary minus for the "example" struct:
void operator- (example &o1) {
  o1.anInt = -o1.anInt;
}

Edited by Fbody: n/a

0

Fbody's solution is a bit bad because it changes the semantics of the built-in operator-. Consider it.

struct example {
  int anInt;
};
 
//Overload the Unary minus for the "example" struct:
void operator- (example &o1) {
  o1.anInt = -o1.anInt;
}

#include <iostream>

void Print(example e)
{
   std::cout << e.anInt;
}
int main()
{
example e1; 
e1.anInt = 4;
example e2 = -e1; //compile error, operator - is void;
Print(-e1) //compile error again, same reason.
}

Much better is, when operator - returns an object.

struct example {
  int anInt;
};
 
//Overload the Unary minus for the "example" struct:
example operator- (const example &o1) { //note the const, good style
  example ret;
  ret.anInt = -o1.anInt;
  return ret;
}

also , the operator can be a member of the class, like this

struct example
 {
  int anInt;
  example operator - () const //note that there are no parameters, well the actual parameter is *this
  {
   example ret;
   ret.anInt = -this->anInt;
   return ret;
  }
};
0

Apologies.

Generally your methods are better, and how I would normally do it. I looked up "overloading C++ unary operators" before I posted just to check some things and I got a link to an IBM website. I found the examples on that page rather odd, so I went to another page (I don't remember what it was) and theirs were similarly formatted. I would have thought IBM's examples would be more authoritative and/or accurate than that, but upon further contemplation I can see the error in them.

Thanks.

Edited by Fbody: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.