【发布时间】:2020-07-24 22:58:55
【问题描述】:
我正在学习 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;
}
【问题讨论】:
标签: c++ oop pointers pass-by-reference pass-by-value