【问题标题】:Swap value of two attributes of two objects交换两个对象的两个属性的值
【发布时间】: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


【解决方案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;
    }

【讨论】:

    【解决方案2】:

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

    将其更改为按引用传递。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-06
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      相关资源
      最近更新 更多