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

时间:2020-04-12 10:28:40

标签: c++ oop pointers pass-by-reference pass-by-value

我正在学习C ++(来自Python),并且试图了解对象之间的交互方式。我想创建一个具有两个属性(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;
}

2 个答案:

答案 0 :(得分:3)

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

将其更改为通过引用。

void swap_coordinates(Point& point) {
//                         ^
    ...
}

答案 1 :(得分:1)

请参阅按引用传递和按值传递概念,这将解决您的问题:

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