交换两个对象的两个属性的值 我正在学习C++(来自Python),我正在尝试了解对象之间如何相互作用。我想创建一个类“Point”,它有两个属性(x和y坐标),并给它一个方法,可以交换两个点的坐标(参见下面的代码)。使用给定代码,点p1的坐标更改为p2的坐标,但p2的坐标保持不变。有人能帮我解释一下我是如何做到这一点的吗
提前谢谢交换两个对象的两个属性的值 我正在学习C++(来自Python),我正在尝试了解对象之间如何相互作用。我想创建一个类“Point”,它有两个属性(x和y坐标),并给它一个方法,可以交换两个点的坐标(参见下面的代码)。使用给定代码,点p1的坐标更改为p2的坐标,但p2的坐标保持不变。有人能帮我解释一下我是如何做到这一点的吗,c++,oop,pointers,pass-by-reference,pass-by-value,C++,Oop,Pointers,Pass By Reference,Pass By Value,提前谢谢 #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){
#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;
}
#包括
使用名称空间std;
//类定义。
类点{
公众:
双x,y;
空集_坐标(双x,双y){
这个->x=x;
这->y=y;
}
无效交换坐标(点){
双温x,双温y;
温度x=此->x;
温度y=此->y;
这->x=点x;
这->y=点y;
点x=温度x;
点y=温度y;
}
};
//主要功能。
int main(){
点p1,p2;
p1.设置_坐标(1,2);
p2.设置_坐标(3,4);
coutswap\u坐标的参数point
被声明为pass by value,它只是参数的副本,对它的任何修改都与原始参数无关
将其更改为通过引用传递
void swap_coordinates(Point& point) {
// ^
...
}
请参阅“按引用传递”和“按值传递”概念,这将解决您的问题:
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;
}