I'm a little confused on how the program reads the math operations for this line:
It seems to me that the way the code is set up it can only add two point objects at a time.Code:Point point4 = point1 + point2 + point3
How does the operator function know how to add the sum of point1 and point2 to point3. Is this where the inline functionCode:Point operator+(const Point &pt) {return add(pt);}comes in?Code:{return add(pt)}
I know this is very basic to some. I'm having a hard time understanding this.
Complete code is below:
Code://this program sets three Point objects to non-negative, then adds them creating //the 4th Point object. #include <iostream> using namespace std; class Point { private: // Data members (private) int x, y; public: // Constructors Point() {}; Point(int new_x, int new_y) {set(new_x, new_y);} Point(const Point &src) {set(src.x, src.y);} // Operations Point add(const Point &pt); Point operator+(const Point &pt) {return add(pt);} // Other member functions void set(int new_x, int new_y); int get_x() const {return x;} int get_y() const {return y;} }; int main() { Point point1(20, 20); Point point2(0, 5); Point point3(-10, 25); Point point4 = point1 + point2 + point3; cout << "The point is " << point4.get_x(); cout << ", " << point4.get_y() << "." << endl; system("PAUSE"); return 0; } void Point::set(int new_x, int new_y) { if (new_x < 0) new_x *= -1; if (new_y < 0) new_y *= -1; x = new_x; y = new_y; } Point Point::add(const Point &pt) { Point new_pt; new_pt.x = x + pt.x; new_pt.y = y + pt.y; return new_pt; }



LinkBack URL
About LinkBacks



