交换两个对象的两个属性的值

Swap value of two attributes of two objects

我正在学习 C++(来自 Python),我正在尝试了解对象之间的交互方式。我想创建一个 class '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;
}

swap_coordinates的参数point被声明为传值,它只是参数的一个副本,任何修改都与原始参数无关。

将其更改为按引用传递。

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;
    }