Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ operator overloading, define negative of object

Tags:

c++

I'm defining a class NS and I want to be able to perform mathematical operations on objects of this class. I, successfully compiled overloaded +, -, *, /, ... My problem is that I can't compile a code which has a part like this:

NS a,b;
a = -b;

How can I define negative of objects?

like image 554
soroosh.strife Avatar asked Apr 27 '13 12:04

soroosh.strife


1 Answers

You do it in a very similar way to overloading the binary - operator. Just instead you make it a nullary function if its a member, or a unary function if it's a non-member. For example, as a member:

class NS
{
  public:
    // Applies to this
    NS operator-() { /* implement */ }
};

As a non-member:

class NS
{
    friend NS operator-(const NS&);
};

// Applies to obj
NS operator-(const NS& obj) { /* implement */ }
like image 135
Joseph Mansfield Avatar answered Oct 18 '22 08:10

Joseph Mansfield