We have following class. I need explanation of some parts of code.
class CPoint3D
{
public:
double x, y, z;
CPoint3D (double dX = 0.0, double dY = 0.0, double dZ = 0.0)
: x(dX), y(dY), z(dZ) {}
//what means these lines of code?
CPoint3D operator + (const CPoint3D& point) const;
CPoint3D operator - (const CPoint3D& point) const;
CPoint3D operator * (double dFactor) const;
CPoint3D operator / (double dFactor) const;
};
I guess using
CPoint3D operator + (const CPoint3D& point) const;
function I can easily add/subtract/multiply/divide instances of CPoint3D
class?
Can someone explain this with examples ? Thanks!
The operator keyword in C++ The keyword operator is used while overloading operators. The syntax for overloading an operator is the following: return_type operator operator's_symbol(parameters){ //... Your code here... } To learn more about overloading operators in c++ you can refer to my article here.
In programming, an operator is a symbol that operates on a value or a variable. Operators are symbols that perform operations on variables and values. For example, + is an operator used for addition, while - is an operator used for subtraction.
C does not support operator overloading (beyond what it built into the language).
There are millions of examples and/or articles of this on the web (including this one) so I won't re-iterate them here.
Suffice to say that when you add together two CPoint3D
objects with obj1 + obj2
, the function that gets called is operator+
for that class, with one object being this
and the other being point
.
Your code is responsible for creating another object containing the addition of those two, then returning it.
Ditto for the subtraction. The multiplicative operators are slightly different since they use a double as the other argument - presumably while it makes some sense to add/subtract individual members of your class for the additive operators, that's not as useful for the multiplicative ones.
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