提问人:user202542 提问时间:4/12/2020 最后编辑:songyuanyaouser202542 更新时间:4/12/2020 访问量:308
两个对象的两个属性的交换值
Swap value of two attributes of two objects
问:
我正在学习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;
}
答:
3赞
songyuanyao
4/12/2020
#1
参数 的 声明为按值传递,它只是参数的副本,对它的任何修改都与原始参数无关。point
swap_coordinates
将其更改为按引用传递。
void swap_coordinates(Point& point) {
// ^
...
}
1赞
Abhishek Kulkarni
4/12/2020
#2
请参阅通过引用传递和按值传递的概念,这将解决您的问题:
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;
}
评论