0

C++ Find the Coordinantes

You are given a Point class, which defines a point on a 2D grid (x, y). The program creates a Point in main based on user input and calls the shift() function, which should increment the coordinates by the given step. However, the code is not working, as the coordinates are private. Modify the code to fix it. #include <iostream> using namespace std; class Point { public: Point(int a, int b): x(a), y(b) {}; void print() { cout << x << ", " << y; } private: int x; int y; }; void shift(Point &p, int step) { p.x += step; p.y += step; } int main() { int x, y; cin>>x>>y; Point p(x, y); int step; cin>>step; shift(p, step); p.print(); } Looking for more than just the answer, if someone could explain the process?

19th Oct 2021, 3:46 PM
Alex Ramsey
3 Respostas
+ 5
This code won't work. For it to work, the class variables x and y have to be public. I'll explain what possibly the writer of the code tried to do here. 1) Created a class Point to store the x and y coordinates of a point. 2) A constructor to create a point object 3) Create a function shift which takes a point object and an integer as parameters. It'll increase the x and y values of the point by that integer 4) The x and y coordinates are taken as inputs from the user, also the shift variable too, then the point object is modified using the "shift()" function, then it's being printed. I'll attach the working code below. All the best =) https://code.sololearn.com/c9GJPdueP8jn/?ref=app Sample input: 5 6 2 Sample output: 7, 8
19th Oct 2021, 4:25 PM
Rishi
Rishi - avatar
+ 1
Thank you!! @Rishi
19th Oct 2021, 5:17 PM
Alex Ramsey
+ 1
Alex Ramsey So I see you tagged the question as friend too. Rishi has provided you the solution but I've made a few changes with the keyword friend, that way you can still keep x and y private I've written the explanation in the code sample https://code.sololearn.com/ceLnUNQ4ry6M/?ref=app You can refer to this lesson for more information on friend https://www.sololearn.com/learning/1899/
19th Oct 2021, 5:50 PM
Tim
Tim - avatar