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 */ }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.