运算符重载( - )将变量设置为0

Wil*_*con 0 c++

当我打电话给r--; 我的对象将值重置为0.任何想法?

class MyClass : Superclass {
private:
    int length;
    int width;

public:
    MyClass() {
        length = 0;
        width = 0;
    }

    MyClass (int x, int y):Superclass(x/2,y/2){
        length = x;
        width = y;

    }

    MyClass operator--(int) {
        MyClass temp = *this;
        temp.length --;
        temp.width --;
        return temp;
    };
};
Run Code Online (Sandbox Code Playgroud)

创建并尝试课程:

MyClass *r = new MyClass(2,3);
r--; // now length and width = 0 (should be 1,2)
Run Code Online (Sandbox Code Playgroud)

Mik*_*our 6

首先,操作符不会减少它所调用的对象,而是它将返回的副本.它应该单独留下(返回前一个值)并减少对象:

MyClass temp = *this;
this->length--;   // this-> is optional
this->width--;
return temp;
Run Code Online (Sandbox Code Playgroud)

其次,r是一个指针.r--递减指针,而不是它指向的对象,使其指向无效的内存位置.之后取消引用会给出未定义的行为.

我不知道你为什么在new这里使用; 你几乎肯定只想要一个变量:

MyClass r(2,3);
r--;   // should behave as expected.
Run Code Online (Sandbox Code Playgroud)

如果由于某种原因确实需要指针,则必须取消引用它才能获取对象:

(*r)--;
Run Code Online (Sandbox Code Playgroud)

并且不要忘记在完成对象后删除它.而不是之前.

  • 它仍然无法工作,因为`operator - (int)`修改`temp`而不是`*this` (2认同)