The code below defines a class Point that represents a point on the coordinate p
ID: 3712470 • Letter: T
Question
The code below defines a class Point that represents a point on the coordinate plane. A Segment should connect two points (its end points). When we make a segment, we will give the constructor the addresses of two points - we want the segment to use those points as its endpoints. The segment should make copies of those points that it owns - if we later change the points, the Segment will not be affected. (Composition)
Finish the Segment class by making a constructor that accepts the addresses of two points and adding member variables.
Code:
#include <iostream>
#include <string>
using namespace std;
class Point {
private:
int x = 0;
int y = 0;
public:
Point(int xVal, int yVal) { moveBy(xVal, yVal); }
string toString() { return to_string(x) + ", " + to_string(y); }
void moveBy(int xVal, int yVal) { x += xVal; y += yVal; }
};
class Segment {
public:
string toString() { return p1.toString() + " to " + p2.toString(); }
//Do not modify anything on or above the line below this
//YOUR_CODE_BELOW
//YOUR_CODE - constructor and member variables
//YOUR_CODE_ABOVE
//Do not modify anything on or below the line above this
};
int main()
{
Point A(0, 0);
Point B(4, 4);
Segment s1(A, B);
cout << s1.toString() << endl;
B.moveBy(1, 1);
cout << s1.toString() << endl;
}
Explanation / Answer
Given below is the completed code according to the specifications in the question.
Please do rate the answer if it was helpful. Thank you
#include <iostream>
#include <string>
using namespace std;
class Point {
private:
int x = 0;
int y = 0;
public:
Point(int xVal, int yVal) { moveBy(xVal, yVal); }
string toString() { return to_string(x) + ", " + to_string(y); }
void moveBy(int xVal, int yVal) { x += xVal; y += yVal; }
};
class Segment {
public:
string toString() { return p1.toString() + " to " + p2.toString(); }
//Do not modify anything on or above the line below this
//YOUR_CODE_BELOW
//YOUR_CODE - constructor and member variables
Segment(Point sp1, Point sp2)
{
p1 = sp1;
p2 = sp2;
}
private:
Point p1 = Point(0,0);
Point p2 = Point(0,0);
//YOUR_CODE_ABOVE
//Do not modify anything on or below the line above this
};
int main()
{
Point A(0, 0);
Point B(4, 4);
Segment s1(A, B);
cout << s1.toString() << endl;
B.moveBy(1, 1);
cout << s1.toString() << endl;
}
output
----
0, 0 to 4, 4
0, 0 to 4, 4
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.