簡體   English   中英

如何為由其他結構/類組成的函數重載遞減(--)運算符

[英]How to overload decrement(--) operator for functions which consist of other structure/classes

如果您的 class 具有 int 值,我發現了很多關於如何重載遞減 (--) 運算符的信息。 但是我不明白如何對包含包含 int 值的結構的類做同樣的事情。 我的意思是:

class Vector{
   Point _end;
   Point _start;
   ...
 }

struct Point {
    int x;
    int y;
   ...
 }

這就是我嘗試為 Vector 重載 operator-- 的方式:

Vector& Vector::operator--() {
    end.x--;
    end.y--;
    return *this;
}
Vector Vector::operator--(int){
    Vector temp = *this;
    *this--;
    return temp;
}

當我對 *this 使用遞減時我也感到疲倦:表達式不可分配那么,我如何以適當的方式重載它?

先感謝您!

這個表情

*this--;

相當於

* ( this-- );

因為后綴運算符的優先級高於一元運算符。

因此嘗試減少指針this

你需要的是

--*this;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM