为什么我的“交换”功能会覆盖类成员? [关闭]

问题描述 投票:0回答:0

我正在用 C++ 创建一个类,它需要一个方法“交换”,它接受另一个相同的类,并且这两个对象应该交换它们其中一个成员的值。相反,一个对象覆盖另一个对象,并且两个对象最终具有相同的值。我尝试在小范围内实现这个以重现问题(见下面的代码)。

我的问题是:

这个交换函数(或类)有什么问题,如何纠正?

#include <iostream>

using namespace std;

class MyClass{
    private:
    int myVal;

    public:
    MyClass(int val){
        myVal = val;
    }
    int getVal(){
        return myVal;
    }
    void setVal(int val){
        myVal = val;
    }
    void printObj(){
        cout << "Value is " << myVal << endl;
    }
    void swap(MyClass other){
        // I know the 'usual' definition is more like:
        // void swap(MyClass& other0, MyClass& other1)
        // I want to understand why this version doesn't work.
        // I also tried making the members public
        // I have also tried using built-in functions like std::swap
        // One of the members in the 'real' example requires a vector,
        // and I tried calling vector.swap, but still no dice.
        // In python you can force an object to copy value by 1*, like:
        // int t_val = 1*myVal;
        // however this didn't work in this case either.

        int t_val = myVal; // Temporary variable, tried with getVal() instead, same behaviour
        myVal = other.getVal(); // replace local with other, also tried setVal(), same behaviour
        other.setVal(t_val); // set other to temporary

        cout << "This value is " << myVal << " other value is " << other.getVal() << endl;
    }
};

int main(){
    MyClass obj0 = MyClass(0);
    MyClass obj1 = MyClass(1);
    obj0.printObj(); // "Value is 0"
    obj1.printObj(); // "Value is 1"
    obj0.swap(obj1); // "This value is 1 other value is 0" <- correct values during swap!
    obj0.printObj(); // "Value is 0" <- Incorrect values after swap
    obj1.printObj(); // "Value is 0"
    return 0;
}

我尝试了所提供代码的各种迭代,包括使成员公开和私有,在各处使用“this->”以确保我正在查看本地值。使用 getters/setters,我还尝试打印出相关变量的地址。但是行为始终是 swap 似乎在 swap 函数期间起作用,但是当它退出时,一个值覆盖另一个值。

我在 C++11 和 C++14 上试过这个,两者的行为相同。

c++ oop memory variable-assignment swap
© www.soinside.com 2019 - 2024. All rights reserved.