// Sample class and client code for a point class that has the same // functionality as the class point.java that we discussed. One of the biggest // differences was that we needed to indicate which member functions are const // member functions for our client code to work properly. #include #include #include #include using namespace std; class point { public: point(int initX = 0, int initY = 0) { setLocation(initX, initY); // the following line of code would not normally be included in a // constructor, but it allowed us to see what point objects were being // constructed cout << "constructing " << to_string() << endl; } // return a string representation of the point string to_string() const { ostringstream out; out << "(" << x << ", " << y << ")"; return out.str(); } // translate the coordinates by the given amount void translate(int dx, int dy) { x += dx; y += dy; } // return the distance from the origin of this point double distance_from_origin() const { return sqrt(x * x + y * y); } // return the x coordinate of this point int getX() const { return x; } // return the y coordinate of this point int getY() const { return y; } // set the coordinates of this point void setLocation(int newX, int newY) { x = newX; y = newY; } private: int x, y; }; // returns a count of the number of points in the given vector that have x and // y values that are equal int count_equal(const vector & points) { int count = 0; for (const point & p : points) { if (p.getX() == p.getY()) { count++; } } return count; } int main() { point p1; point p2; p2.setLocation(3, 18); point p3(13, 5); cout << "p1 = " << p1.to_string() << endl; cout << "p2 = " << p2.to_string() << endl; cout << "p3 = " << p3.to_string() << endl; cout << endl; p1.translate(3, 8); cout << "p1 now = " << p1.to_string() << endl; cout << endl; cout << "p1 distance from origin = " << p1.distance_from_origin() << endl; cout << "p2 distance from origin = " << p2.distance_from_origin() << endl; cout << "p3 distance from origin = " << p3.distance_from_origin() << endl; cout << endl; vector v; for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { v.push_back(point(i, j)); } } cout << "number of equal points = " << count_equal(v) << endl; return 0; }