r--; 내 개체 값을 0으로 다시 설정합니다. 어떤 아이디어?연산자 오버로드 (-)는 변수를 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;
};
};
작성 및 클래스를 시도 :
MyClass *r = new MyClass(2,3);
r--; // now length and width = 0 (should be 1,2)
'r -'는 포인터를 감소시키고 있으므로'r'은 할당 한 객체를 가리 키지 않습니다. 그것을 가리키는 것을 사용하거나 보려고하면 정의되지 않은 동작이 발생합니다. –
운영자는 복사본에있는 것이 아닌'this-> length'와'this-> width'을 수정해야합니다. postfix 연산자는'this'를 수정하고 이전에 객체 상태의 복사본을 반환해야하므로'temp.length -;'를'length -;'로 대체하고'width'를 위해서는 ditto를 사용해야합니다. – cdhowie
진술 :'MyClass :: operator -()'로'MyClass :: operator - (int)'를 구현해야합니다. – Deduplicator