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?
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 */ }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With