Suppose I define this structure:
struct Point {
double x, y;
};
How can I overload the +
operator so that, declared,
Point a, b, c;
double k;
the expression
c = a + b;
yields
c.x = a.x + b.x;
c.y = a.y + b.y;
and the expression
c = a + k;
yields
c.x = a.x + k;
c.y = a.y + k; // ?
Will the commutative property hold for the latter case? That is, do c = a + k;
and c = k + a;
have to be dealt with separately?
In C++, we can change the way operators work for user-defined types like objects and structures. This is known as operator overloading. For example, Suppose we have created three objects c1 , c2 and result from a class named Complex that represents complex numbers.
This means C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading. For example, we can overload an operator '+' in a class like String so that we can concatenate two strings by just using +.
An overloaded operator (except for the function call operator) cannot have default arguments or an ellipsis in the argument list. You must declare the overloaded = , [] , () , and -> operators as nonstatic member functions to ensure that they receive lvalues as their first operands.
(::) Scope resolution operator cannot be overloaded in C language. Operator overloading:- It is polymorphism in which an operator is overloaded to give user-defined meaning to it. The overloaded operator is used to perform operations on user define data type.
Just do it:
Point operator+( Point const& lhs, Point const& rhs );
Point operator+( Point const& lhs, double rhs );
Point operator+( double lhs, Point const& rhs );
With regards to your last question, the compiler makes no
assumptions concerning what your operator does. (Remember, the
+
operator on std::string
is not commutative.) So you
have to provide both overloads.
Alternatively, you can provide an implicit conversion of
double
to Point
(by having a converting constructor in
Point
). In that case, the first overload above will handle
all three cases.
Here is how I would do it.
struct Point {
double x, y;
struct Point& operator+=(const Point& rhs) { x += rhs.x; y += rhs.y; return *this; }
struct Point& operator+=(const double& k) { x += k; y += k; return *this; }
};
Point operator+(Point lhs, const Point& rhs) { return lhs += rhs; }
Point operator+(Point lhs, const double k) { return lhs += k; }
Point operator+(const double k, Point rhs) { return rhs += k; }
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