Я изучаю C ++ (из Python) и пытаюсь понять, как объекты взаимодействуют друг с другом. Я хотел создать класс 'Point', который имеет два атрибута (координаты x и y) и дать ему метод, который может менять координаты двух точек (см. Мой код ниже). С данным кодом координаты точки p1 изменяются на координаты p2, но координаты p2 остаются неизменными. Кто-нибудь может мне помочь и объяснить, как мне этого добиться?
Заранее спасибо!
#include<iostream>
using namespace std;
//Class definition.
class Point {
public:
double x,y;
void set_coordinates(double x, double y){
this -> x = x;
this -> y = y;
}
void swap_coordinates(Point point){
double temp_x, temp_y;
temp_x = this -> x;
temp_y = this -> y;
this -> x = point.x;
this -> y = point.y;
point.x = temp_x;
point.y = temp_y;
}
};
//main function.
int main(){
Point p1,p2;
p1.set_coordinates(1,2);
p2.set_coordinates(3,4);
cout << "Before swapping the coordinates of point 1 are (" << p1.x << ","<< p1.y<<")\n";
cout << "and the coordinates of point 2 are ("<< p2.x << ","<< p2.y << ").\n";
p1.swap_coordinates(p2);
cout << "After swapping the coordinates of point 1 are (" << p1.x << ","<< p1.y<<")\n";
cout << "and the coordinates of point 2 are ("<< p2.x << ","<< p2.y << ").\n";
return 0;
}