Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator Overloading in struct

Tags:

c++

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?

like image 945
wjm Avatar asked Nov 20 '12 18:11

wjm


People also ask

What is operator overloading in data structure?

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.

What is operator overloading with example?

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 +.

Which operators can be overloaded in C++?

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.

Which operators Cannot be overloaded?

(::) 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.


2 Answers

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.

like image 188
James Kanze Avatar answered Sep 22 '22 03:09

James Kanze


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; }
like image 34
Robᵩ Avatar answered Sep 26 '22 03:09

Robᵩ