struct PT
{
double x, y;
PT() {}
PT(double x, double y) : x(x), y(y) {}
PT(const PT &p) : x(p.x), y(p.y) {}
PT operator + (const PT &p) const { return PT(x+p.x, y+p.y); }
PT operator - (const PT &p) const { return PT(x-p.x, y-p.y); }
PT operator * (double c) const { return PT(x*c, y*c ); }
PT operator / (double c) const { return PT(x/c, y/c ); }
};
This code snippet is from http://stanford.edu/~liszt90/acm/notebook.html#file8 . I am not able to understand this piece of code . Someone please explain this . I know that this is operator overloading but am not able to understand how exactly operator overloading is taking place.
Can someone explain these lines also:
PT() {}
PT(double x, double y) : x(x), y(y) {}
PT(const PT &p) : x(p.x), y(p.y) {}
Do structures also have constructors ?
Declares two local, class variables that make up the class.
Default constructor. Allows you to create a PT without any arguments.
e.g. –>
PT myObj;Constructor to create a point from two doubles.
e.g. –>
PT myObj(3.5, 9.0);After the declaration –> PT(double x, double y) : x(x), y(y) {}
we have initialisation .–> PT(double x, double y) : x(x), y(y) {}
x(x)is equivalent tothis->x = x;i.e. initialise the class variable ‘x’ with the constructor parameter ‘x’. It is somewhat confusing that they have given the parameters the same name as the class variables. A better example might have been:
Copy constructor to create a PT object from another PT object
e.g. –>
PT myOtherObj(myObj);Addition and subtraction operators to get the sum or difference of two points to make a third.
e.g. –>
PT operator * (double c) const { return PT(x*c, y*c ); }PT operator / (double c) const { return PT(x/c, y/c ); }Multiplication and division operators to multiply (or divide) a point by a constant.
e.g. –>