c++ - 交换两个对象的两个属性的值

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

我正在学习 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;
}

最佳答案

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

将其更改为按引用传递。

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

关于c++ - 交换两个对象的两个属性的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61170025/

相关文章:

c# Matrix of pictureBox 的

c++ - Qt C++ XML 意外字符

oop - 为什么代理商和经理被认为是糟糕的 O-O 设计

python - 有人可以帮我在 pygame 中为扑克游戏创建一副纸牌吗

c - 二维数组充满垃圾数据......有时

c++ - C/C++ 指针保存用户数据吗?

c++ - 奇怪的错误,set<int>::begin() 总是返回 const 迭代器

c++ - Linux 宽字符串到多字节问题

c++ - 如何在子类中访问父类(super class)中的私有(private)成员变量?

language-agnostic - 对应的正确 OO 建模