簡體   English   中英

在C ++中實現單調整數,而不必重載基本運算符

[英]Implement a monotonic integer in C++ without having to overload basic operators

我想實現一個只會隨着時間增加的整數類。 因此,如果i是值為v的單調整數,則不能為其分配小於v的值。 我可以使用重載=運算符的類來實現此功能,但是我不想為int+,-,+=,-=等重新定義所有有用的運算符。有沒有辦法做到這一點? 我不確定是否可以使用轉換為intwrapper class

您將不得不重新定義運算符。 創建一個自定義類,僅定義支持所需功能的方法。 例如,

class IncInt{

    int m_value;

public:
    explicit IncInt(int start) : m_value(start) {}
    const IncInt& operator=(const IncInt& obj)
    {
        if(this == &obj)
            return *this;

        if(obj.m_value > m_value)
            m_value = obj.m_value;
        return *this;
    }

    const IncInt& operator=(const int n)
    {
        if(n > m_value)
            m_value = n;
        return *this;
    }

    IncInt operator+(const int n) const
    {
        return IncInt(m_value + n);
    }

    // additional functions
};

暫無
暫無

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

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